DEV Community

Robert McIntosh
Robert McIntosh

Posted on

Solving the Weekly Challenge 302 Task 2: Step by Step in Python

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.

The Weekly Challenge 302, Task 2: Step by Step

Examples 1 - 3 present the expected outputs from given inputs.

Example 1

Input: @ints = (-3, 2, -3, 4, 2)
Output: 5
Enter fullscreen mode Exit fullscreen mode

For start value 5.

5 + (-3) = 2
2 + (+2) = 4
4 + (-3) = 1
1 + (+4) = 5
5 + (+2) = 7
Enter fullscreen mode Exit fullscreen mode

Example 2

Input: @ints = (1, 2)
Output: 1
Enter fullscreen mode Exit fullscreen mode

Example 3

Input: @ints = (1, -2, -3)
Output: 5
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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 each start_value:
    • I calculate the step-by-step sum (step_sum) of start_value and ints[0]. If step_sum is less than one, then I start over with the next possible start_value.
    • I calculate step_sum for the remaining elements of ints. If step_sum is less than one for any element, then I start over with the next possible start_value.
    • If the final step_sum for start_value is greater than one, then I return start_value.
  • If I do not find a start_value within the range of [1, 1000000), then I return None.

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)