This program shows how to calculate the max in a list using the very useful reduce fn. from functools
It also shows how to use a lambda function, again something that every Pythonista should know.
The program below will work for any list (just change list in main()), and also demonstrates industry-standard code for writing Python applications
from functools import reduce
def max_in_list(li): # uses lambda function and reduce (list to single value)
return reduce(lambda a, b: a if a > b else b, li)
def run_max_tests(lst):
print('............. beginning test on max_in_list...................')
max_values = []
for i in range(1, len(lst) + 1):
slice = lst[:i] # a slice of the first i values in the list
# get max for slice, save in max_values list
max_values.append(max_in_list(slice))
# uses Python f-Strings, lst[-1] is its last value
print(f'{max_values[-1]} == max of {slice}')
print('-' * 10)
for el in max_values: # print out again, one value at a time w/o list
print(el)
print('................. ending test on max_in_list..................\n')
def main():
lst = [1, 0, 3, 2, 9, 8]
run_max_tests(lst=lst)
if __name__ == '__main__':
main()
# ===================================================================
# OUTPUT
# ===================================================================
# .................. beginning test on max_in_list...................
# 1 == max of [1]
# 1 == max of [1, 0]
# 3 == max of [1, 0, 3]
# 3 == max of [1, 0, 3, 2]
# 9 == max of [1, 0, 3, 2, 9]
# 9 == max of [1, 0, 3, 2, 9, 8]
# ----------
# 1
# 1
# 3
# 3
# 9
# 9
# ...................... ending test on max_in_list..................