I’m a beginner at Python and I’m getting a strange out of bounds error.
The idea is that I need a cache initialized using:
arr = [0]*1000000
then accessed in the same function by calling
def func (i) :
k=1
a = i
arr = [0]*1000000
while (i>1):
if arr[i] != 0:
k = k + arr[i] - 1
break
if i%2 == 0:
i = i/2
else:
i = 3*i + 1
k += 1
arr[a] = k
return k
if the value i is over 1500 it gives me an out of bounds error. The cache, however, is supposed to be initialized to a million ints. Am I missing something? Thanks
Updated now that the code is posted:
I don’t seem to get any problems up to 1500. I do get an IndexError for
func(1819), for which the i evolution beginsand winds up at
but that’s not a bug, that’s simply a fact that it goes higher than you made room for. You could use a dictionary instead of a list to avoid this problem.
—
To be clear, here’s the sort of thing I had in mind:
which produces
and a final answer of 162. I don’t think I’d use
arrthis way myself, though, but what I would do depends upon what you’re trying to do.