简体   繁体   中英

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

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.

Ie,

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

print(sum(mylist))

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.

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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM