I’ve been working on the Project Euler problems to try and learn python and I wrote a solution to the second problem (find the sum of even-valued terms in the Fibonacci sequence that do not exceed four million). The code gives me the correct solution, but it requires me to use modulus division twice in order to remove the odd-numbered values from the list of fibonacci numbers I generated. Here is the solution I wrote:
term_1 = 1
term_2 = 2
fibonacci_list = [1]
while term_2 < 4000000:
fibonacci_list.append(term_2)
term_1, term_2 = term_2, term_1 + term_2
for num in fibonacci_list:
if num % 2 != 0
fibonacci_list.remove(num)
for num in fibonacci_list:
if num % 2 != 0
fibonacci_list.remove(num)
return sum(fibonacci_list)
If I only put in one for-loop, the list fibonacci_list becomes the following:
[2, 5, 8, 21, 34, 89, 144, 377, 610, 1597, 2584, 6765, 10946, 28657, 46368, 121393, 196418, 514229, 832040, 2178309, 3524578]
Shouldn’t all the odd numbered terms fail the modulus division test and be removed? Why do I need to run the for loop twice to remove all odd numbered terms?
I imagine the problem you are facing is that you are attempting to remove items from a list while iterating over the list.
See here, here and here for previous questions on this same topic.
For the sake of discussion, let’s assume this is in fact the problem, and let’s assume that it is forbidden to remove items from a list while iterating over it.
What could you do differently that would result in you not needing to remove items from a list while iterating over it? I’m not sure if you want to be given the answer outright or not since you are doing Project Euler, so I will refrain from giving out any obvious answers.