77. Runs that add up to k
A run is one or more items that stand next to each other in a list. Write a function count_runs(numbers, k) that
takes a list of whole numbers and a whole number k, and returns how many runs add up to exactly k.
- Runs are counted by position: two runs with the same numbers at different places count twice.
- The numbers can be negative or zero, so a run can add up to
kagain after growing longer. In[1, -1, 0]three runs add up to 0:[1, -1],[0]and[1, -1, 0].
Trying every start and end takes about n * n / 2 runs. With negative numbers a sliding window doesn't work either, because a growing run can get smaller. There is a one-pass way: keep a running total, and use a dictionary to count how often each running total has come up so far.
Example 1
numbers = [1, 1, 1], k = 22Example 2
numbers = [1, 2, 3], k = 32Example 3
numbers = [1, -1, 0], k = 03Constraints
numbershas 1 to 200 whole numbers, each from -1000 to 1000.kis a whole number from -10^5 to 10^5.
Submit also runs 8 more tests you can't see.
Practises Dictionaries (lesson 11).
- Keep a running total of the items so far. The run from just after position
iup to the current item adds up to (total now) - (total ati). - So the runs ending at the current item that add up to
kare the earlier points where the running total wastotal - k. A dictionary can count how many times each total has come up. - Start the dictionary with
{0: 1}: the total before any item is 0, which lets a run start at the very first item. Add each new total to the dictionary after counting.
Solve it without hints for 3 stars, with hints for 2, after seeing the solution for 1.
One way to solve it, once you've had a go.
Solving it after seeing the solution earns 1 star.
Your Submits show here, with their code, so you can go back to one. They stay in this browser.
def count_runs(numbers, k):
"""Count the runs of consecutive items that add to k.
numbers: list of int, at least one; may be negative
k: int, the total to look for
Returns: int, how many runs (one or more items in a
row) add up to exactly k
"""
# Write your code here
pass
Run your code to see how it does on the test cases, or Submit to check every test.