Answer the question
In order to leave comments, you need to log in
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)
Answer the question
In order to leave comments, you need to log in
import numbers
b = sorted([x for x in a if isinstance(x, numbers.Number)])
sum(b[-2:])
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 questionAsk a Question
731 491 924 answers to any question