max array

Go Back home

Iterative

1 A = [0,1,0,2,1,0,1,3,2,1,2,1]
2 max_l, m = [], 0
3 for a in A:
4 m = max(a, m)
5 max_l.append(m)
6 print(max_l)

Output:

1 [0, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 3]

Generative

1 A = [0,1,0,2,1,0,1,3,2,1,2,1]
2 def max_array_from_left(A):
3     m = 0
4     for a in A:
5         m = max(a, m)
6         yield m
7 
8 print([*max_array_from_left(A)])

Output:

1 [0, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 3]

Functional

1 from itertools import accumulate
2 
3 A = [0,1,0,2,1,0,1,3,2,1,2,1]
4 
5 accumulate(A, lambda a, b: b if b > a else a)

Output:

1 [0, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 3]

See also

max array from right