Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use reduce function here? [duplicate]

I am trying to find total of all the integers in a tuple

from  functools  import reduce
marks =  [("Jon" ,29 ), ("santi",35), ("anna",35)]

Total_marks = lambda x,y: x[1]

print(marks)
print (reduce(Total_marks,marks))

The above code can take the first value of integer, but i want to find the sum of all the integers, how to do it using reduce in python

like image 236
Karamzov Avatar asked Sep 13 '26 17:09

Karamzov


2 Answers

Change the definition of the adding function (there is no need to use lambda notation here):

def total_marks(x, y): 
    return x + y[1]

And tell reduce that the initial value is a number, not a tuple, by providing the third optional parameter:

reduce(total_marks, marks, 0)
#99

The same solution with lambda:

reduce(lambda x,y: x+y[1], marks, 0)

And one more solution that does not use reduce:

_, y = zip(*marks)
sum(y)
#99
like image 114
DYZ Avatar answered Sep 16 '26 07:09

DYZ


If using reduce is not necessary, a much more elegant solution is

marks =  [("Jon" ,29 ), ("santi",35), ("anna",35)]
total_marks = sum(score for _, score in marks)
print(total_marks)
like image 36
lakshayg Avatar answered Sep 16 '26 06:09

lakshayg