-1

Here is my code:

def f(x): return x%2!=0 and x%3!=0

primes = filter(f , range (6,50))

for x in primes:
    for a in filter(f, range(2,x-1)):       
      if x%a == 0:
        primes.remove(x);

print(primes)

I get this error:

File "primes.py", line 12, in <module>
    primes.remove(x);
ValueError: list.remove(x): x not in list

But the funny thing is if i write like that:

def f(x): return x%2!=0 and x%3
primes = filter(f , range (6,20))

for x in primes:
    for a in filter(f, range(2,x-1)): 

            if x%a == 0:
                primes.remove(x);

print(primes)

Why? and how can i fix it?

4

2 回答 2

1

让我们输入一些打印语句来看看发生了什么:

In [81]: %paste
def f(x): return x%2!=0 and x%3!=0

primes = filter(f , range (6,50))
print primes

for x in primes:
    for a in filter(f, range(2,x-1)):
      if x%a == 0:
        print x
        primes.remove(x);

print(primes)

## -- End pasted text --
[7, 11, 13, 17, 19, 23, 25, 29, 31, 35, 37, 41, 43, 47, 49]
25
35
35

因此,您的问题是您两次生成数字 35 (第二次出现异常,因为第一次删除后它不存在!)

于 2013-09-03T05:46:57.917 回答
0

让我们看看结果:

>>> primes = filter(f , range (6,50))
>>> primes
[7, 11, 13, 17, 19, 23, 25, 29, 31, 35, 37, 41, 43, 47, 49]

您在这里的值为 35,即 5*7。在您的嵌套循环中,当a为 5 时,满足条件并从primes; 列表中删除 35。当a转到 7 时,再次满足条件,但是这次 35 已经被移除,因此引发了异常。

所以一个简单的固定就像下面的一样。这样x在第一次满足条件时只删除一次:

for x in primes:
    for a in filter(f, range(2,x-1)):
        if x%a == 0:
            primes.remove(x)
            break

但现在它将跳过非质数之后的元素,例如此列表中的 95:

primes=[7, 11, 13, 17, 19, 23, 25, 29, 31, 35, 37, 41, 43, 47, 49, 53, 55, 59, 61, 65, 67, 71, 73, 77, 79, 83, 85, 89, 91, 95, 97]

这是通过制作切片来修复的primes

for x in primes[:]:
    for a in filter(f, range(2,x-1)):
        if x%a == 0:
            primes.remove(x)
            break
于 2013-09-03T05:41:05.483 回答