这些天我在python中设计了一些算法,但是发现python中的前两个最大值太丑陋且效率低下。
如何以高效或 Python 的方式实现它?
大多数 Pythonic 方式是使用nlargest
:
import heapq
values = heapq.nlargest(2, my_list)
我发现这始终比heapq.nlargest
:
def two_largest(sequence):
first = second = 0
for item in sequence:
if item > second:
if item > first:
first, second = item, first
else:
second = item
return first, second
(功能根据 MatthieuW 的建议修改)
以下是我的测试结果(timeit
需要永远,所以我使用了time.time()
):
>>> from random import shuffle
>>> from time import time
>>> seq = range(1000000)
>>> shuffle(seq)
>>> def time_it(func, *args, **kwargs):
... t0 = time()
... func(*args, **kwargs)
... return time() - t0
...
>>> #here I define the above function, two_largest().
>>> from heapq import nlargest
>>> time_it(nlargest, 2, seq)
0.258958101273
>>> time_it(two_largest, seq)
0.145977973938
mylist = [100 , 2000 , 1 , 5]
mylist.sort()
biggest = mylist[-2:]
a=int(input('Enter the first number:'))
b=int(input('Enter the second Number:'))
c=int(input('Ente the Third Number:'))
if a>b and a>c:
print('the value of A is',a,'highest velue')
elif b>a and b>c:
print('the value of B is',b,'highest velue')
elif c>a and c>b:
print('the value of C is',c,'highest velue')
else:
print('the value is equls')