Reputation: 119
Here is the python code :
x=[2, 3, 5, 7]
for i in range(1, 5000):
if i%2:
if i%3:
if i%5:
if i%7:
x.append(i)
x.remove(1)
a = 6
b = 2
for i in range(0, 10):
a = x[a - b]
b = x[a] - x[b]
I get an IndexError: list index out of range
for some reason, even though x[] is 1360 and a is just 6 while b is 2 so I dont know why it is happening. Any help would be nice.
I am using the python shell. Would that be a problem?
Upvotes: 1
Views: 58
Reputation: 2586
The problem of your code is your logic in the for loop.
You see:-
a = 6
b = 2
for i in range(0, 10):
a = x[a - b]
b = x[a] - x[b]
Yes a was 6 & b was 2, but then when you enter your for loop for the first time, a's value is
x[a-b] which is x[6-2]
i.e. x[4] which gives you 11
so a's value is 11, likewise for b,
b = x[a] - x[b] # which translates to x[11] - x[2]
which becomes b=32 & the loop goes on jumping/changing the values of a & b which leads you to IndexError: list index out of range
which is expected.
Try executing your program in pycharm & debug it, you would understand it better, or maybe just put some print statements.
I could not type so much in a comment, hence posted it as an answer.
Upvotes: 1