Reputation: 4790
I am using a lambda function to check the highest value, passing 3 arguments
from functools import reduce
# function to check bigger item
f = lambda a,b,c: a if (a > b) else (b if (b > c) else c)
# reduce function
reduce(f, [47, 11, 42, 102, 13])
However I get an error like this
TypeError Traceback (most recent call last)
5 6 # reduce function 7 reduce(f, [47, 11, 42, 102, 13, 21]) TypeError: <lambda>() missing 1 required positional argument: 'c'
Upvotes: 1
Views: 2410
Reputation: 17322
for checking the highest value use the build-in function max:
max([47, 11, 42, 102, 13])
Upvotes: 1
Reputation: 4199
If you are looking for the biggest elements in the list, compare three elements in once works in the same way as compare two elements in once. the two ways cost the same time. and even you make a function like reduce
but takes 3 elements a time, there is a defect in your idea, because what if the list is composed of 4 or 6 or 8 or... elements, It still won't work as you expected.
from functools import reduce
# function to check bigger item
g = lambda a,b: a if (a > b) else b
f(1,3,4)
# reduce function
reduce(g, [47, 11, 42, 102, 13])
Upvotes: 3
Reputation: 58
From: https://docs.python.org/3/library/functools.html
functools.reduce(function, iterable[, initializer])
Apply function of two arguments cumulatively to the items of sequence, from left to right, so as to reduce the sequence to a single value.
So, reduce is designed for functions with 2 arguments.
Upvotes: 2