w3resource

Python: Generate the running maximum, minimum value of the elements of an iterable


3. Max & Min from Iterable

Write a Python program to generate the maximum and minimum values of the elements of an iterable.

Sample Solution:

Python Code:

from itertools import accumulate
def running_max_product(iters):
    return accumulate(iters, max)
#List
result = running_max_product([1,3,2,7,9,8,10,11,12,14,11,12,7])
print("Running maximum value of a list:")
for i in result:
    print(i)
#Tuple
result = running_max_product((1,3,3,7,9,8,10,9,8,14,11,15,7))
print("Running maximum value of a Tuple:")
for i in result:
    print(i)
def running_min_product(iters):
    return accumulate(iters, min)
#List
result = running_min_product([3,2,7,9,8,10,11,12,1,14,11,12,7])
print("Running minimum value of a list:")
for i in result:
    print(i)
#Tuple
result = running_min_product((1,3,3,7,9,8,10,9,8,0,11,15,7))
print("Running minimum value of a Tuple:")
for i in result:
    print(i)

Sample Output:

Running maximum value of a list:
1
3
3
7
9
9
10
11
12
14
14
14
14
Running maximum value of a Tuple:
1
3
3
7
9
9
10
10
10
14
14
15
15
Running minimum value of a list:
3
2
2
2
2
2
2
2
1
1
1
1
1
Running minimum value of a Tuple:
1
1
1
1
1
1
1
1
1
0
0
0
0

For more Practice: Solve these Related Problems:

  • Write a Python program to generate the maximum and minimum values from an iterable after applying a transformation to each element.
  • Write a Python program to create an iterator that yields tuples containing both the running maximum and minimum values from an iterable.
  • Write a Python program to compute the max and min of an iterable where elements are first filtered based on a condition using a lambda.
  • Write a Python program to find the maximum and minimum of an iterable by comparing elements pairwise using itertools.reduce.

Go to:


Previous: Write a Python program to create an iterator from several iterables in a sequence and display the type and elements of the new iterator.
Next: Write a Python program to construct an infinite iterator that returns evenly spaced values starting with a specified number and step.

Python Code Editor:


Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.