Project Euler Problem 2 in Python with Error Message

Viewed 102

I am a complete beginner in coding and was trying problems from Project Euler in Python. Could anyone please explain what is wrong with my code? Problem: 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.

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))

I received the error message "cannot unpack non-iterable int object". What does this message mean and how to avoid it?

2 Answers

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"

x = y, y = x + y

When i take away the addition from the end and the assignment from the beginning, the error still is there.

y, y = x

Output : an error. about non-iterable int ! Because you can unpack an iterable.

iterable = [0, 1, 2]
zero = iterable[0]
one = iterable[1]
two = iterable[2]

is not very good (sorry for my bad english ...) to use, because you have to type iterable[n] again and again. That's why you can unpack such iterables like this:

iterable = [0, 1, 2]
zero, one, two = iterable

This will produce the same result as the above long version.

Back to your code,

x = y, y = x + y

the python interpreter will first work on the assignment (x = ...). To resolve it, it tries to unpack x + y into two values, but this is not possible of course.

To declare two variables on one line, you have to separate the assignments with a colon ;, not a comma. But when you do just that, x will have the same value as y at the beginning, and so y will then be the double of itself, which surely is not what you wanted. Maybe you should do it like this ?

a = []
x = 1
y = 2

for y in range (1, 400000):
  if x % 2:
    a.append(x)
  x, y = y, x + y
  # above is equivalent to
  # temp = y
  # y = x + y
  # x = temp
print(sum(a))
Related