-1

I am working of Project Euler problem 2. I need to find the sum of all even Fibonacci numbers up to four million. I have a function that generates all possible Fibonacci numbers up to upperBound which is input by the user. I am passing this list of fibs to another function in order to eliminate the odd values. I am trying to iterate through the list and delete the element if it is odd. It is returning an error saying :

in evenFibs
    del list_of_fibs[value]
IndexError: list assignment index out of range

Here is my code for evenFibs() :

def evenFibs(upperBound):
    list_of_fibs = getFibs(upperBound)
    for value in list_of_fibs:
        if value % 2 != 0:
            del list_of_fibs[value]
    return list_of_fibs

I am not sure why this error is occuring.

Seanzy
  • 27
  • 3
  • 4
    Not a good idea to remove items from a list while iterating over it :) – dfranca Oct 23 '15 at 14:06
  • You should use the method in the accepted answer from Ben's link. If you're curious why your method doesn't work, try reading through the answers to http://stackoverflow.com/questions/10812272/modifying-a-list-while-iterating-over-it-why-not – jgloves Oct 23 '15 at 14:13
  • Begs the question, why aren't you building a list of even numbers as you go? Then you wouldn't have to worry about removing them in the first place. – Rolf of Saxony Oct 23 '15 at 14:47
  • @RolfofSaxony good point, but if I had thought of that I wouldn't have learned about list comprehension! – Seanzy Oct 23 '15 at 16:22
  • You never learn from success, only from failure and the more you fail the more you learn, hopefully ;) – Rolf of Saxony Oct 24 '15 at 09:24

1 Answers1

0

Take a note that you shouldn't change array while iterating it, also to delete element from array you should use index of element, not value. You can get index of first element with specific value using index method of list. As for your task, it would be better to use list comprehension:

def evenFibs(upperBound):
    list_of_fibs = getFibs(upperBound)
    return [value for value in list_of_fibs if value % 2 == 0]
Eugene Soldatov
  • 9,755
  • 2
  • 35
  • 43
  • From your statement and reading some of the links, am I correct in understanding that by deleting an element from my array, I am altering the index value of the other elements...therefore making it possible to skip certain elements during the iteration? – Seanzy Oct 23 '15 at 14:32
  • You can skip elements using `continue` statement. – Eugene Soldatov Oct 23 '15 at 14:34