Why is the function not printing the sum of the values in the list?
这个程序的目标是让函数"fib"接受两个值,并将它们放入一个fibonacci序列中,在变量"sequence"执行过程中向其添加项。当它通过"check"函数并返回达到的限制时,它将向列表"final"添加偶数值,然后循环打印出"final"的和。
问题是,无论FIB采用什么值,最终结果总是没有值。我对编程很陌生,似乎不明白为什么要这样做…
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | 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 |
如果列表中的第一项小于20,则
你可能是说:
1 2 3 4 5 6 | def check(sequence): for v in sequence: if v >= 20: return 'Limit Reached' else: return None |
此代码有许多问题。我会这样写的:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | 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 |
仍然可以进一步简化,但这个结构与您自己的结构相匹配。实际上,甚至不需要保留
您不会返回final,所以每次调用fib()时都会清除它的值,因为它是一个局部变量。我相信它能打印出预期的结果,是吗?
也许你想要更简单的东西:
1 2 3 4 5 6 7 8 9 10 11 | 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 |
与大多数语言不同的是,python会在这样的拼写错误上抛出运行时错误(而不是根本不编译程序)。
1 | final.apppend(even(v)) |
如果没有看到运行时错误,说明周围的