Fibonacci sequence

################################################################################
#Question:                                                                     #
#Each new term in the Fibonacci sequence is generated by adding                #
#the previous two terms. By starting with 1 and 2, the first 10 terms will be: #
#                                                                              #
#    1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...                                    #
#                                                                              #
#By considering the terms in the Fibonacci sequence whose values do not exceed #
#four million, find the sum of the even-valued terms                           #
#By IT05 2012-08-14
################################################################################


#one
s = [1,2]
while s[-1]<=4000000:
    s.append(s[-1]+s[-2])
print(sum([i for i in s if i%2==0]))

#two
b = [3,5]
s = [2]
while s[-1]<=4000000:
    s.append(sum(b))
    b = [b[1]+s[-1],b[1]+s[-1]+s[-1]]
s.pop()
print(sum(s))

for i in s:
    if i%2==1:
        s.remove(i)
        print('remove:'+str(i))

一开始是想把结果里面的不合要求的数踢出,

于是用这段代码,然后想通过直接执行

print(sum(s))

即可获得所需结果,但是问题就出现了.(先不探讨,这种方法吃力不讨好)
因为在remove()的过程中会导致s元组发生改变,这样的话,由于for一开
始是假定元组s是不变的,它是通过类似的索引来读取元组的,虽然这个我
没有查到资料,但是我在测试中有这种规律,比如执行如下代码:

s = [1,2]
while s[-1]<=4000000:
    s.append(s[-1]+s[-2])
print(s)
#循环1
for i in s:
    if i%2==1:
        s.remove(i)
print(s)
#循环2
for i in s:
    if i%2==1:
        s.remove(i)
print(s)

最后的结果是:
[1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987,...]
[2, 5, 8, 21, 34, 89, 144, 377, 610, 1597, 2584, 6765, 10946,...]
[2, 8, 34, 144, 610, 2584, 10946, 46368, 196418, 832040, 3524578]
假定上面三行分别命名为A,B,C行
那么在循环1执行时,第一次循环发现1%2不为1,所以把1踢掉,如此是s=[2,3,...],
即s[0]=2,在执行第二次循环时,相当于执行索引1,即此时i=s[1],要是s没变的话,
很好,s[1]还是2,但是现在变了,变成了3,所以此时会把s[1]踢掉,所以s=[2,5,8,....]
执行第三次循环时,相当于索引2,即i=s[2],由于s[2]=8,s所以不作处理,但是我们
回过头却发现那个5因为偷偷地跑到前面去了,导致循环执行完之后,5被漏掉了。


后来回头想了下,其实没必要这么做的,直接把符合要求的提出来即可!


原文地址:https://www.cnblogs.com/arbboter/p/4225238.html