Here is the code:
import math as m
primeproduct = 5397346292805549782720214077673687806275517530364350655459511599582614290
primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181]
def pseudoroot(n):
print(n)
for i in n:
if n[i] > m.sqrt(primeproduct):
return n[i-1] #greatest divisor below the root
psrprime = pseudoroot(primes)
Running this code gives this error:
Traceback (most recent call last):
File "so.py", line 11, in <module>
print(pseudoroot(primes))
File "so.py", line 7, in pseudoroot
if n[i] > m.sqrt(primeproduct):
IndexError: list index out of range
Which really doesn't make any sense to me as the i in the for loop is a given index in the list and shouldn't exceed the bounds of that list.
You've confused the list index with the list contents.
for i in n
means thati
will take on the values ofn
in sequence: 2, 3, 5, 7, 11, ...From Python's point of view ...
n
has 42 elements. As soon as you get to accessingn[i]
when i is 43, you crash.Try this:
Do note that this fails in your MCVE, because you don't have enough primes to get to sqrt(primeproduct).
for i in n
iterates over the values not the indicies. If you want the indicies there are a couple ways you could do it, one beingfor i, v in enumerate(n)
and then you can usev
instead ofn[i]
.Not quite.
i
is an item in your list, not an index.for i in n
gives you the items inn
. Not the index. So doingn[i]
is a bit nonsensical (you're using the items as indices). A quick fix is to usefor i in range(len(n))
if you want a c-style index.More pythonic would be: