W
W
weranda2016-04-07 10:53:51
Python
weranda, 2016-04-07 10:53:51

How to correctly solve the problem of finding the two maximum numbers in a list?

Greetings
I came across a task: find the two maximum numbers from the list and find their sum. I just came up with this simple idea:

a = [1,2,39,4,13,4,5,6,7,3,23,2]

a.sort()

a = a[-2] + a[-1]

print(a)

But the list can also contain textual data.
How to solve correctly and elegantly?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Gornostaev, 2016-04-07
@weranda

import numbers
b = sorted([x for x in a if isinstance(x, numbers.Number)])
sum(b[-2:])

Option without sorting:
import numbers
import heapq

b = [x for x in a if isinstance(x, numbers.Number)]
sum(heapq.nlargest(2, b))

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question