Python IndexError: list index out of range when us

2020-04-22 06:45发布

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.

3条回答
Ridiculous、
2楼-- · 2020-04-22 07:19

You've confused the list index with the list contents. for i in n means that i will take on the values of n in sequence: 2, 3, 5, 7, 11, ...

From Python's point of view ... n has 42 elements. As soon as you get to accessing n[i] when i is 43, you crash.

Try this:

def pseudoroot(n):
    for i, p in enumerate(n):
        if p > m.sqrt(primeproduct):
            return n[i-1] #greatest divisor below the root

Do note that this fails in your MCVE, because you don't have enough primes to get to sqrt(primeproduct).

查看更多
狗以群分
3楼-- · 2020-04-22 07:45

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 being for i, v in enumerate(n) and then you can use v instead of n[i].

查看更多
Bombasti
4楼-- · 2020-04-22 07:45

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.

Not quite. i is an item in your list, not an index.

for i in n gives you the items in n. Not the index. So doing n[i] is a bit nonsensical (you're using the items as indices). A quick fix is to use for i in range(len(n)) if you want a c-style index.

More pythonic would be:

for before_prime, current_prime in zip(n, n[1:]):
    if current_prime > m.sqrt(primeprod):
        return before_prime #greatest divisor below the root
查看更多
登录 后发表回答