100 XP

77. Runs that add up to k

Advanced dictionaries lists

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 k again 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

Inputnumbers = [1, 1, 1], k = 2
Output2
ExplanationThe first two 1s, and the last two.

Example 2

Inputnumbers = [1, 2, 3], k = 3
Output2
Explanation[1, 2] and [3].

Example 3

Inputnumbers = [1, -1, 0], k = 0
Output3
Explanation[1, -1], [0] and [1, -1, 0].

Constraints

  • numbers has 1 to 200 whole numbers, each from -1000 to 1000.
  • k is a whole number from -10^5 to 10^5.

Submit also runs 8 more tests you can't see.

Practises Dictionaries (lesson 11).

Code
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