Another question asked to compute cumulative maximum of a list in a list comprehension, e.g.:
input: [3, 4, 2, 8, 9, 3, 3, 4, 20, 1]
output: [3, 4, 4, 8, 9, 9, 9, 9, 20, 20]
I came up with a decent list comprehension there as requested, but it uses that the input is given as a list:
[m
for m in list_input[:1]
for x in list_input
for m in [max(m, x)]]
My question/challenge: What if the input is an iterator or any other iterable? Should still be just a list comprehension and take only linear time. And of course not using accumulate(iterable, max)
. I found one and I like it, but would like to see other people's solutions as well :-)
Testing code, leaving cumulative_maximum
to implement (Try it online!):
from itertools import accumulate
def cumulative_maximum(iterable):
return [your list comprehension here]
def test(iterable):
iterable = tuple(iterable)
expect = list(accumulate(iterable, max))
output = cumulative_maximum(iterable)
print(output == expect, output)
output = cumulative_maximum(iter(iterable))
print(output == expect, output)
test([3, 4, 2, 8, 9, 3, 3, 4, 20, 1])
test([])
test([3])
test([3, 1])