So I have been running into a really weird error. I have a module ten.py containing
import math
def go():
list_ = list(range(3, 100000, 2))
max_ = int(math.sqrt(len(list_)))
print(len(list_))
print(max_)
for i in range(1,max_):
print(i)
current = list_[i]
for j in list_[i+1:]:
if j % i == 0:
list_.remove(j)
go()
The output is this:
49999
223
1
2
Traceback (most recent call last):
File "D:\Documents\KomodoProjects\Project Euler\ten.py", line 14, in <module>
go()
File "D:\Documents\KomodoProjects\Project Euler\ten.py", line 10, in go
current = list_[i]
IndexError: list index out of range
As you can see the size of list is 49999 and the for loop only goes to 223. Despite all this it already gives an index out of range exception at index=2!
Is the list_ inside the for loop somehow not referencing to the list_ inside go()? I have no clue as to why this problem occurs.
Fixed by changing
for i in range(1,max_):
to
for i in list_:
Here is your problem:
You have a
forloop that is deleting numbers fromlist_. It is deleting so many numbers thatlist_is length 2, and thenlist_[2]fails and raises an exception.The reason it is deleting so many numbers is that you are computing
x % 1 == 0which is true for any value of x. Since you start at position 2 in the list, you are deleting everything after that position.I’m not certain exactly what you are doing but this is going to be a slow way to do it, whatever it is. This looks sort of like screening for prime numbers… you might want to do a Google search for “Python find prime numbers” or something.