Mubtasim
Mubtasim

Reputation: 347

How to sum numbers from list(s) in python?

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

Upvotes: 2

Views: 5444

Answers (4)

Robert
Robert

Reputation: 8767

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)

Upvotes: 1

Levon
Levon

Reputation: 143027

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

Upvotes: 4

xiaowl
xiaowl

Reputation: 5207

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

Upvotes: 0

Ned Batchelder
Ned Batchelder

Reputation: 375484

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.

Upvotes: 2

Related Questions