Reputation: 197
I'm given a lambda function and a 2D list. It must be done with reduce()
. Let's say:
func=lambda x,y:x+y
input=[[2,3],[4,5]]
# OUTPUT should be [[5],[9]]
All I got is:
arr=[]
arr.append(reduce (lambda x,y:x+y,[i for i in input[0]]))
arr.append(reduce (lambda x,y:x+y,[i for i in input[1]]))
return arr
# OUTPUT here is [5,9]
Is there any better solution?
Upvotes: 0
Views: 271
Reputation: 755
Just surround the call to reduce
with [...]
.
Example: arr.append([reduce(lambda x,y: x+y,input[0]]))
Also, there's no need to use a comprehension in the call to reduce
, as I have shown in the example above.
Finally, as @Roman Kh pointed out, this can all be compressed into one statement: arr = [reduce(lambda x,y: x+y, item) for item in input]
Upvotes: 0