2

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

Karamzov
  • 343
  • 1
  • 4
  • 12

4 Answers4

3

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
DYZ
  • 55,249
  • 10
  • 64
  • 93
3

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)
lakshayg
  • 2,053
  • 2
  • 20
  • 34
  • this is easy and can u post the full code – Karamzov Jul 09 '18 at 02:10
  • @Karamzov I have updated the code – lakshayg Jul 09 '18 at 02:12
  • How does the sum and for works here, how they knew to read the values ? – Karamzov Jul 09 '18 at 02:20
  • `sum` is a builtin function is python which can be used to sum iterables (lists, tuples, generators etc). The interesting part here is `score for _, score in marks`. This is what is called a list comprehension. A comment would be too short to explain what it does, please see this [blog](http://treyhunner.com/2015/12/python-list-comprehensions-now-in-color/). Googling "list comprehensions in python" will help too. – lakshayg Jul 09 '18 at 02:24
  • ok ... helpful .... – Karamzov Jul 09 '18 at 02:25
  • I changed the first set as `(2,29)` and run the code but still my result is 99 , not 101 , from your code how the list comprehension knows to sum the second value in list – Karamzov Jul 10 '18 at 08:06
2

You would use operator.itemgetter(1) to get the numbers out of the tuple, and reduce with operator.add to sum them

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

print(reduce(add, map(itemgetter(1), marks)))
# 99

A simpler solution without reduce is sum(mark for name, mark in marks)

Patrick Haugh
  • 59,226
  • 13
  • 88
  • 96
1

You can check if the first parameter (x) is a tuple:

from functools import reduce
marks = [("Jon" ,29 ), ("santi",35), ("anna",35)]
new_marks = reduce(lambda x, y:(x if isinstance(x, int) else x[-1])+y[-1], marks)
assert new_marks == sum(b for _, b in marks)
print(new_marks)

Output:

99
Ajax1234
  • 69,937
  • 8
  • 61
  • 102