简体   繁体   English

Python for循环:“列表索引超出范围”错误?

[英]Python for loop: “list index out of range” error?

I have a code, based on problem 3 from Project Euler: "The prime factors of 13195 are 5, 7, 13 and 29. What is the largest prime factor of the number 600851475143?" 我有一个代码,基于欧拉计画的问题3:“ 13195的素数是5、7、13和29。600851475143的最大素数是多少?”

I have a code below that I thought would work, but line 9 ( for k in range(2,res[j]): ) keeps returning the error: "IndexError: list index out of range". 我下面有一个我认为可以使用的代码,但是第9行( for k in range(2,res[j]): )不断返回错误:“ IndexError:列表索引超出范围”。 It doesn't seem like I'm modifying my list as I move through my for loop, so I'm not sure what's wrong. 在遍历for循环时,似乎没有在修改列表,所以我不确定出什么问题。

def find_primes(num):
    res = []
    print(num)

    for i in range(2,num):
        if num%i==0:
            res.append(i)

    for j in res:
        for k in range(2,res[j]):
           if res[j]%k==0:
               res[j]=False
    list(filter((False).__ne__, res))

    m = max(res)
    return(m)

Does anyone know where I'm going wrong? 有谁知道我要去哪里错了?

Thank you! 谢谢!

You probably meant to do: 您可能打算这样做:

for j in range(len(res)):
    for k in range(2,res[j]):

Using for j in res will iterate over res elements. for j in res使用for j in res将遍历res元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM