这个程序的目标是让'Fib'函数接收两个值,然后通过Fibonacci序列,在变量'sequence'中添加术语。当它通过'check'函数并返回Limit Reached时,它会将偶数值添加到列表'final',然后在循环后打印出'final'的总和。
问题是无论Fib接受什么值,'final'总是没有值。我对编程很陌生,似乎无法弄清楚为什么会这样做......
def even(x):
v = list(str(x))[-1]
if v == '0' or v == '2' or v == '4' or v == '6' or v == '8':
return x
else:
return 0
def check(sequence):
for v in sequence:
if v >= 20:
return 'Limit Reached'
else:
return None
def Fib(x,y):
sequence = [x,y]
a = 0
b = 1
final = []
while len(sequence) < 100:
term = sequence[a] + sequence[b]
sequence.append(term)
if check(sequence) == 'Limit Reached':
for v in sequence:
final.apppend(even(v))
print sum(final)
break
a += 1
b += 1
答案 0 :(得分:4)
check
将始终返回None
。
你可能意味着:
def check(sequence):
for v in sequence:
if v >= 20:
return 'Limit Reached'
else:
return None
答案 1 :(得分:2)
此代码存在许多问题。我会这样写的:
def even(x):
# is the modulo operator, it's used to calculate a remainder
return x % 2 == 0
def check(sequence):
# you need to check all the values, not just the first one
return max(sequence) >= 20
def Fib(x, y):
sequence = [x, y]
while len(sequence) < 100:
# it's not necessary to keep a and b around, you can use
# negative indices instead
sequence.append(sequence[-2] + sequence[-1])
if check(sequence):
# this is called a "generator comprehension"
print sum(v for v in sequence if even(v))
break
仍然可以进一步简化,但这种结构与您自己的结构相匹配。实际上没有必要保持sequence
,因为你可以随时保持一个总计,但我认为这样做会更有启发性。
答案 2 :(得分:1)
你没有返回final,所以每次调用Fib()时它的值都被清除,因为它是一个局部变量。我确定它会打印出预期的结果,不是吗?
答案 3 :(得分:0)
与大多数语言不同,Python会在这样的拼写错误上抛出运行时错误(而不是根本不编译你的程序)。
final.apppend(even(v))
没有看到运行时错误表明永远不会满足周围的if
条件,这是因为check
方法在检查序列中的第一项后立即返回,而不是检查整个序列。
答案 4 :(得分:0)
也许你想要更简单的东西:
def fib(a, b, iterations = 20):
result = 0
if not (a & 1): result += a
if not (b & 1): result += b
for x in xrange(iterations):
nextval = a + b
if not (nextval & 1):
result += nextval
a = b
b = nextval
return result