Хабр Курсы для всех
РЕКЛАМА
Практикум, Хекслет, SkyPro, авторские курсы — собрали всех и попросили скидки. Осталось выбрать!
import mathImportError: __import__ not foundTwo-sum
Write a function to return the sum of the two largest elements in the given list (assuming you're given a list with at least two elements).
Hint: Can you find the largest element? How about the second largest? Or think about sorting.
Solution: Scan through the list twice to find the two largest elements, then sum them (or sort and sum the two largest elements).
def sumTwoLargest(lst):
max = -9223372036854775807
prevMax = max
for el in lst:
if max < el:
prevMax = max
max = el
else:
if prevMax < el:
prevMax = el
return max+prevMax
def sumTwoLargest(lst):
return sorted( lst )[::-1][0]
def sumTwoLargest(lst):
return sum( sorted( input )[-2:] )
Python 2.6.5
для первого решения время :
real 0m1.905s
user 0m1.840s
sys 0m0.068s
для второго решения время :
real 0m0.881s
user 0m0.748s
sys 0m0.092s
строка запуска print sumTwoLargest( range( 1, 10000444 ))
First the trivial cases, trivial for samplesort because it special-cased
them, and trivial for timsort because it naturally works on runs. Within
an «n» block, the first line gives the # of compares done by samplesort,
the second line by timsort, and the third line is the percentage by
which the samplesort count exceeds the timsort count:
x = 5
def foo(y):
def bar():
for i in range(x,y):
yield i
return bar
it = foo(7)
for z in it():
print z
Онлайн-репетитор по Python