i=2
_sum=0
a={0:1,1:2} #you cannot give value to a index that not exist in List
while True:
a[i]=a[i-1]+a[i-2]
if a[i]>4000000: #break condition
break
if (i%3==1): #only this item is even-valued
_sum+=a[i]
i+=1
print _sum+2
这代码龊的一比啊,这是在写C语言吧,靠。弄了两个pythonic的代码来学习下。
s = 0
a, b = 1, 1
while a < 4000000:
a, b = b, a+b
if a%2 == 0:
s += a
print s
a = [1,2]
i = 2
while a[-1] < 4000000:
a.append(a[i-2] + a[i-1])
i += 1
print sum(filter(lambda x: x%2 == 0, a))
这两段都是阿三哥写的,转自PE的论坛,hk97和hkapur97。