1

In a list of python tuple, I need to find the tuple with min sum.

for example,

a = [ (2, 6) , (1,3) , (0,2) ]

(0, 2) should be returned because its sum is minimal.

I know how to do it by list comprehension and then find the smallest tuple sum.

 minTuple = min([((x[0] + x[1]), (x[0], x[1])) for x in a ], key = lambda x : x[0] )

I would like to do it by map/lambda and list comprehension.

How to implement it efficiently?

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
user3448011
  • 1,469
  • 1
  • 17
  • 39

2 Answers2

3

The simplest answer to your question is just to use the min() function, provided with a key to the array. The key parameter specifies a set of rules for comparison that min() uses to evaluate the tuples.

See answer here.

min(a, key=sum)

Evan Weissburg
  • 1,564
  • 2
  • 17
  • 38
2

Try this!

>>> a = [ (2, 6) , (1,3) , (0,2) ]
>>> min(a, key=sum)
(0, 2)

>>> a = [ (2, 6) , (1,3) , (0,7) ]
>>> min(a, key=sum)
(1, 3)
Javier
  • 1,027
  • 14
  • 23