问题描述
基于Euler项目的问题3,我有一个代码:"13195的素数是5、7、13和29.600851475143数中最大的素数是多少?"
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?"
我下面有一个我认为可以使用的代码,但是第9行(for k in range(2,res[j]):
)始终返回错误:"IndexError:列表索引超出范围".在遍历for循环时,似乎没有在修改列表,所以我不确定这是怎么回事.
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". 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.
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?
谢谢!
推荐答案
您可能打算这样做:
for j in range(len(res)):
for k in range(2,res[j]):
使用for j in res
将遍历res
个元素.
这篇关于Python for循环:“列表索引超出范围"错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!