为什么我的橡皮擦筛子不起作用?Python3

2024-10-03 19:27:17 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我的密码。我试图做一个有效但简单的erastotenes筛选,但当我运行程序时,它只会不断返回整数,不管我把范围放多大。这是在python3中。你知道吗

lyst = []
for i in range(2, 100):
    print(i)
    lyst.append(i)
count = 2
index = 1
for x in lyst:
    print(str(index) + " : " + str(count))
    if x%count == 0 and x != count:
        lyst.remove(x) #removing all multiples of count
    if max(lyst) == count: #breaks loop if count is the largest prime
        break
    else:
        count = lyst[lyst.index(count)+1] #turns count into next prime
    index += 1 #this is just for me to track how many primes i've found

Tags: in程序密码forindexifiscount
3条回答

xcount的值将始终具有相同的值:

  • 一开始是这样的,值2
  • 因此remove将不执行
  • 迭代结束时,count将是列表中的下一个值,这正是下一次迭代开始时的值

结论:它们在每次迭代开始时具有相同的值,因此if条件永远不会满足。你知道吗

第二,Erasthotenes的筛子不应该从筛子中除去元素,而是将某些值标记为非素数。它的功能是将值保持在原始索引,因此.remove()实际上不应该出现在纯筛算法中。你知道吗

要获得找到正确实现的灵感,您可以查看以下几个答案:

这是您的代码和wikipedia description的混合体:

n = 100
lyst = range(2, n)
for p in lyst:
    if not p:
        continue
    for i in range(2*p,n,p):
      lyst[i-2] = None
print [p for p in lyst if p]
#=> [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]

这应该可以。。。看看移除倍数的内部循环:

lyst = []
max = 100 # because ... you know, variables. ...
for i in range(2, max):
    lyst.append(i)
count = 2
index = 1
for x in lyst:
    print(str(index) + " : " + str(x)) # x is a prime number, so print it
    for y in lyst:
        if y>x and y%x == 0:
            lyst.remove(y)

    index += 1 #this is just for me to track how many primes i've found
print(index) # how many did we find 

相关问题 更多 >