2

Learning python for two days :) and now I attempting to solve Project Euler problem #2 and I need help.

To be more specific, I need know know how to add numbers that were added to a empty list. I tried 'sum' but doesn't seems to work how the tutorial sites suggest. I'm using python 3. Here's my code so far:

a = 0
b = 1
n = a+b
while (n < 20):
   a, b = b, a + b
   n = a+b
   if n%2 == 0:
       mylist = []
       mylist.append(n)
       print(sum(mylist))

this outputs:

2
8

Now how do I add them? Thanks :)

2
  • So, you're asking Python to take the sum of a list with one element. What do you actually want to take the sum of? Commented Jul 15, 2012 at 3:30
  • @inspectorG4dget There's no input, it's generating a Fibonacci sequence, see the problem description: projecteuler.net/problem=2 Commented Jul 15, 2012 at 3:42

4 Answers 4

4

You are doing it right (the summing of the list), the main problem is with this statement:

mylist = []

move it before the while loop. Otherwise you are creating an new empy mylist each time through the loop.

Also, you probably want to print the sum of the list probably after you are done with your loop.

I.e.,

...
mylist = []
while (n < 20):
   a, b = b, a + b
   n = a+b
   if n%2 == 0:
       mylist.append(n)

print(sum(mylist))
Sign up to request clarification or add additional context in comments.

Comments

2

You are creating a new empty list just before you append a number to it, so you'll only ever have a one-element list. Create the empty mylist once before you start.

Comments

1

Since it seems that you have the list issue resolved, I would suggest an alternative to using a list.

Try the following solution that uses integer objects instead of lists:

f = 0
n = 1
r = 0

s = 0

while (n < 4000000):
    r = f + n
    f = n
    n = r
    if n % 2 == 0:
        s += n

print(s)

Comments

0

Just as @Ned & @Levon pointed out.

a = 0
b = 1
n = a+b
mylist = []
while (n < 20):
   a, b = b, a + b
   n = a+b
   if n%2 == 0:
       mylist.append(n)
print(sum(mylist))

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.