← Practice
πŸ“– The itertools moduleitertools-running-max
LessonΒ·difficulty 2/5Β·~15 min

itertools: running maximum

itertools: running maximum

itertools.accumulate walks a sequence and emits a running result. By default it adds, but pass any two-argument function and it folds with that instead:

python
import itertools
list(itertools.accumulate([1, 2, 3, 4]))         # [1, 3, 6, 10]  (running sum)
list(itertools.accumulate([1, 2, 3, 4], max))    # [1, 2, 3, 4]   (running max)

For each position it combines "the result so far" with "the next item". With max, the result so far can only ever grow β€” it's the biggest value seen up to and including that index.

Your task

Write running_max(nums) that returns a list where each element is the maximum of nums up to that position. Use itertools.accumulate with max and wrap it in list(...).

python
running_max([3, 1, 4, 1, 5])   # [3, 3, 4, 4, 5]
running_max([1])               # [1]
running_max([])                # []
running_max([5, 4, 3])         # [5, 5, 5]

Note: an empty input yields an empty list β€” accumulate simply produces nothing to fold.

Tests

  • rises and plateaus
  • single element
  • empty list
  • monotonic down
  • negatives (hidden)
  • strictly rising (hidden)

✦ Stuck? Ask for a spark

warming up
Loading editor…

$ Console output will appear here.

>_AI tutor
Sign in to chat with the tutor.