Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Hello Seamonkey and welcome to SO. I am happy that you have put more effort into this question than your last :)</p> <p>I am going to walk through the code with you step by step. For simple problems, I find that it is easier to <em>not</em> use functions, as they can be annoying when one has to deal with global variables</p> <pre><code>#This part of the code gets the entire fibonacci sequence list_of_numbers = [] even_fibs = [] x,y = 0,1 #sets x to 0, y to 1 while y &lt;= 4000000: #Gets numbers till 4 million list_of_numbers.append(y) x, y = y, x+y #updates the fib sequence </code></pre> <p>In this block of code, (you can change it to a function if you wish), we calculate the full fibonacci sequence, up to 4 million. We also create two lists, <code>list_of_numbers</code> and <code>even_fibs</code>. The first is used to store the full sequence, the second is used to help us to store the even numbers. On to the next block. </p> <pre><code>coord = 0 for number in range(len(list_of_numbers)): test_number = list_of_numbers [coord] if (test_number % 2) == 0: even_fibs.append(test_number) coord+=1 </code></pre> <p>Here I tested if numbers within the list <code>list_of_numbers</code> were even. If they were, I added them to the <code>even_fibs</code> list. You can read up on lists <a href="http://www.sthurlow.com/python/lesson06/" rel="nofollow">here</a>.</p> <pre><code>print "Normal: ", list_of_numbers #outputs full sequence print "\nEven Numbers: ", even_fibs #outputs even numbers print "\nSum of Even Numbers: ", sum(even_fibs) #outputs the sum of even numbers </code></pre> <p>This simply outputs our findings. </p> <hr> <p>Since you seem to be fond of functions, I added the code here. The explanation is the same as it is up top.</p> <pre><code>#This part of the code gets the entire fibonacci sequence list_of_numbers = [] even_fibs = [] def fib(list_of_numbers): x,y = 0,1 #sets x to 0, y to 1 while x+y &lt;= 4000000: #Gets numbers till 4 million list_of_numbers.append(y) x, y = y, x+y #updates the fib sequence return list_of_numbers def even(list_of_numbers, even_fibs): coord = 0 for number in range(len(list_of_numbers)): test_number = list_of_numbers [coord] if (test_number % 2) == 0: even_fibs.append(test_number) coord+=1 return even_fibs fib(list_of_numbers) #call fib function even(list_of_numbers, even_fibs) #Call the even function #Output print "Normal: ", list_of_numbers print "\nEven Numbers: ", even_fibs print "\nSum of Even Numbers: ", sum(even_fibs) </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload