1. Introduction
The Weekly Challenge, organized by Mohammad S. Anwar, is a friendly competition in which developers compete by solving a pair of tasks. It encourages participation from developers of all languages and levels through learning, sharing, and having fun.
Task 2: Step by Step from The Weekly Challenge requires developers to find a starting value that makes a step-by-step sum never smaller than one.
In this post I discuss, and present my Python language solution to, Task 2: Step by Step, and wrap with a brief conclusion.
2. Task 2: Step by Step
You are given an array of integers,
@ints
.Write a script to find the minimum positive start value such that the step by step sum is never less than one.
Examples 1 - 3 present the expected outputs from given inputs.
Example 1
Input: @ints = (-3, 2, -3, 4, 2)
Output: 5
For start value 5.
5 + (-3) = 2
2 + (+2) = 4
4 + (-3) = 1
1 + (+4) = 5
5 + (+2) = 7
Example 2
Input: @ints = (1, 2)
Output: 1
Example 3
Input: @ints = (1, -2, -3)
Output: 5
3. My solution to Task 2
def return_min_start(ints: list[int]) -> int | None:
for start_value in range(1, 1000000):
step_sum = start_value + ints[0]
if step_sum < 1:
continue
for index in range(1, len(ints)):
step_sum += ints[index]
if step_sum < 1:
break
if step_sum >= 1:
return start_value
return None
My solution uses for
loops and if
statements to incrementally search for the start_value
that matches the task requirements:
- I incrementally search for starting values within the range of
[1, 1000000)
. For eachstart_value
:- I calculate the step-by-step sum (
step_sum
) ofstart_value
andints[0]
. Ifstep_sum
is less than one, then I start over with the next possiblestart_value
. - I calculate
step_sum
for the remaining elements ofints
. Ifstep_sum
is less than one for any element, then I start over with the next possiblestart_value
. - If the final
step_sum
forstart_value
is greater than one, then I returnstart_value
.
- I calculate the step-by-step sum (
- If I do not find a
start_value
within the range of[1, 1000000)
, then I returnNone
.
4. Conclusion
In this post I discussed Task 2: Step by Step and I presented my solution.
Learn more about the latest and past challenges at The Weekly Challenge website:
https://theweeklychallenge.org/
Learn more about competing at The Weekly Challenge FAQ:
https://theweeklychallenge.org/faq/
Top comments (0)