55. Best k in a row
Write a function best_window(numbers, k) that takes a list of whole numbers and a whole number k, and returns the
largest total of k items that stand next to each other in the list.
- The
kitems must be consecutive:numbers[i]tonumbers[i + k - 1]for somei. Picking theklargest items from all over the list doesn't count. - Numbers can be negative, and so can the answer: when every total is below 0, return the least negative one.
kis at least 1 and at most the length of the list.
Adding up every group of k from scratch repeats a lot of work. Moving from one group to the next, only one item
comes in and one goes out.
Example 1
numbers = [3, -1, 4, 1, 5, -9, 2], k = 310Example 2
numbers = [-2, -3, -1], k = 2-4Example 3
numbers = [5], k = 15Constraints
numbershas 1 to 200 whole numbers, each from -1000 to 1000.kis from 1 tolen(numbers).
Submit also runs 8 more tests you can't see.
Practises For Loops (lesson 13).
- Start with the first group's total,
sum(numbers[:k]), and make it the best so far. Starting the best at 0 goes wrong when every total is negative. - Slide the window one place right: the item at
icomes in and the one ati - kgoes out, sowindow += numbers[i] - numbers[i - k]. - Do that for every
ifromktolen(numbers) - 1(range(k, len(numbers))), keeping the largest total. The last group ends at the last item.
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 best_window(numbers, k):
"""Find the biggest total of k items in a row.
numbers: list of int, at least one
k: int, from 1 to len(numbers)
Returns: int, the largest sum of k consecutive items
"""
# Write your code here
pass
Run your code to see how it does on the test cases, or Submit to check every test.