编辑
更好的解决方案
不尝试使用列表推导。改为使用递归。
与我以前的解决方案相比,更简单,执行时间除以 3。
LastCoin=[0, 1, 2, 1, 2, 5, 1, 2, 1, 2, 5, 1, 2,
1, 2, 5, 1, 2, 1, 2, 5, 1, 2, 1, 2, 5,
1, 2, 1, 2, 5, 1, 2, 1]
def nekst(x,L,rec=None):
if rec is None: rec = []
rec.append(L[x])
if x-L[x]>0: nekst(x-L[x],L,rec)
return rec
print nekst(33,LastCoin)
结果
[1, 2, 5, 5, 5, 5, 5, 5]
比较执行时间
注意:以下测试是使用没有行的递归函数完成的
if rec is None: rec = [].
这条线的存在稍微增加了 (+12%) 具有递归函数的解决方案的执行时间。
from time import clock
iterat = 10000
N = 100
LastCoin=[0, 1, 2, 1, 2, 5, 1, 2, 1, 2, 5, 1, 2,
1, 2, 5, 1, 2, 1, 2, 5, 1, 2, 1, 2, 5,
1, 2, 1, 2, 5, 1, 2, 1]
counter = 33
te = clock()
for i in xrange(iterat):
final_list = [LastCoin[reduce(lambda x, y: x - LastCoin[x],
range(counter, i, -1))]
for i in range(counter -1, 0, -1)
if reduce(lambda x, y: x - LastCoin[x],
range(counter, i, -1))]
print clock()-te,'Omid Raha'
st=33
E1 = []
for n in xrange(N):
te = clock()
for i in xrange(iterat):
susu2 = [st]
susu2.extend(x for x in xrange(st,0,-1)
if x==(susu2[-1]-LastCoin[susu2[-1]]))
fifi2 = [LastCoin[x] for x in susu2]
del fifi2
E1.append(clock()-te)
t1 = min(E1)
print t1,'eyquem 1'
E2 = []
for n in xrange(N):
te = clock()
for i in xrange(iterat):
def nekst(x,L,rec):
rec.append(L[x])
if x-L[x]>0: nekst(x-L[x],L,rec)
return rec
fifi3 = nekst(st,LastCoin,[])
del fifi3,nekst
E2.append(clock()-te)
t2 = min(E2)
print t2,'eyquem 2, nekst redefined at each turn of the measurement loop'
def nekst(x,L,rec):
rec.append(L[x])
if x-L[x]>0: nekst(x-L[x],L,rec)
return rec
E22 = []
for n in xrange(N):
te = clock()
for i in xrange(iterat):
fifi3 = nekst(st,LastCoin,[])
del fifi3
E22.append(clock()-te)
t22 = min(E22)
print t22,'eyquem 2, nekst defined outside of the measurement loop'
W = []
for n in xrange(N):
te = clock()
for i in xrange(iterat):
y = 33
final_list=[]
while y>0:
final_list.append(LastCoin[y])
y-=LastCoin[y]
del final_list,y
W.append(clock()-te)
tw = min(W)
print tw,'while-loop == %.1f %% of %s' % (100*min(W)/min(E22),min(E22))
结果
4.10056836833 Omid Raha
0.29426393578 eyquem 1
0.114381576429 eyquem 2, nekst redefined at each turn of the measurement loop
0.107410299354 eyquem 2, nekst defined outside of the measurement loop
0.0820501882362 while-loop == 76.4 % of 0.107410299354
如果函数nekst()的定义在时序循环之外执行,会快一点。
.
原始答案略有编辑
我没有比这更好的了:
sum=33
LastCoin=[0, 1, 2, 1, 2, 5, 1, 2, 1, 2, 5, 1, 2,
1, 2, 5, 1, 2, 1, 2, 5, 1, 2, 1, 2, 5,
1, 2, 1, 2, 5, 1, 2, 1]
susu = [sum]
susu.extend(x for x in xrange(sum,0,-1)
if x==(susu[-1]-LastCoin[susu[-1]]))
fifi = [LastCoin[x] for x in susu]
print 'susu == %r\n'\
'fifi == %r\n'\
'wanted : %r' % (susu,fifi,[1, 2, 5, 5, 5, 5, 5, 5])
结果
susu == [33, 32, 30, 25, 20, 15, 10, 5]
fifi == [1, 2, 5, 5, 5, 5, 5, 5]
wanted : [1, 2, 5, 5, 5, 5, 5, 5]
。
编辑是:
x for x in xrange(sum,0,-1) if x==(susu[-1]-LastCoin[susu[-1]])
代替原来的
x for x in xrange(sum,-1,-1) if x==(susu[-1]-LastCoin[susu[-1]])!=0