首页 > 解决方案 > 带有错误消息的 Python 中的 Project Euler 问题 2

问题描述

我是一个完全的编码初学者,并且正在尝试 Python 中的 Project Euler 中的问题。谁能解释我的代码有什么问题?问题:斐波那契数列中的每个新项都是通过添加前两项来生成的。从 1 和 2 开始,前 10 个术语将是:

1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...

通过考虑斐波那契数列中值不超过四百万的项,求偶数项之和。

a = []
x = 1
y = 2

for y in range (1, 400000):
  if x % 2:
    a.append(x)
  x = y, y = x + y


print(sum(a))

我收到错误消息“无法解压缩不可迭代的 int 对象”。此消息是什么意思以及如何避免它?

标签: python

解决方案


You get that error because you have the line x = y, y = x + y which is interpreted as an attempt to unpack values from an iterable into y, y, so you need to have a new line between x = y and y = x + y.

However since x is assigned with the value of y before y is updated, the better option is to change the line to x, y = y, x + yas JackTheCrab suggested in a comment.

Look the below example as well to explain the error:

price, amount = ["10$", 15] #iterable that can be unpacked
price, amount = 15 # this is just an int and this row will throw error "Cannot unpack non-iterable int object"

推荐阅读