1

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'
2
  • 1
    how many arguments do you think reduce passes? are you actually passing 3 args? (and if you think that that's not how it should work, just consider. lambda is just a way to write a function, but any function works. why should reduce be introspecting the function passed for number of args?) Commented Aug 3, 2019 at 11:03
  • 2
    reduce function expects/compares 2 items, not 3 Commented Aug 3, 2019 at 11:03

3 Answers 3

3

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])
Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

1

for checking the highest value use the build-in function max:

max([47, 11, 42, 102, 13])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.