为什么我列出素数的简单程序告诉我“builtin_function_or_method”

程序卡在第 7 行并打印错误


“'builtin_function_or_method' 对象不可下标”


这段代码可能有更多错误,因为我是一个完整的新手,如果您发现任何错误,请指出。


i = 3

primes = [2]

remainder = []

while i <= 20:

    for x in primes:

        remainder.append[i%x]

    if all(remainder!= 0) == True:

        primes.append(i)

    i += 1

    remainder.clear()

print(primes)

我希望代码做的是遍历数字 3 到 20,每次通过除以所有已知素数来检查我是否是素数,如果是素数,我希望代码将其附加到已知素数列表中以便它可以用于测试 i 的进一步值的素性。


慕斯王
浏览 176回答 3
3回答

慕容708150

append[i%x]与交换append(i%x)。append是一个内置方法。方括号[]用于子集/索引。而是使用括号调用该函数()。因此,例如,以下代码将起作用:primes = [2]remainder = []for i in range(3, 21): # range slightly more often used than while loops&nbsp; &nbsp; for x in primes:&nbsp; &nbsp; &nbsp; &nbsp; remainder.append(i%x)&nbsp; &nbsp; if all(remainder): # note: no reason to add "== True". See PEP8.&nbsp; &nbsp; &nbsp; &nbsp; primes.append(i)&nbsp; &nbsp; remainder.clear()print(primes)

子衿沉夜

另一种实现可能是:def is_prime(n):&nbsp; &nbsp; """&nbsp; &nbsp; Check whether the given number is prime or not.&nbsp; &nbsp; """&nbsp; &nbsp; # we dont need to check all the range of numbers&nbsp; &nbsp; # from [2, n). We need to check in the set [2, n/2]&nbsp; &nbsp; # Note: there is an even better approximation&nbsp; &nbsp; for num in range(2, n/2 + 1):&nbsp; &nbsp; &nbsp; &nbsp; if n % num == 0:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return False&nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp; return Truedef all_primes(limit):&nbsp; &nbsp; """&nbsp; &nbsp; Find all prime numbers in the range [2, limit)&nbsp; &nbsp; """&nbsp; &nbsp; primes = []&nbsp; &nbsp; for num in range(2, limit):&nbsp; &nbsp; &nbsp; &nbsp; if is_prime(num):&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; primes.append(num)&nbsp; &nbsp; return primesprint all_primes(20)

SMILET

您的代码现在有两个问题。首先,您需要替换[]为()因为append是一个函数。其次,在您目前的实现中,您将有一段TypeError: 'bool' object is not iterable时间检查all(). 您可以简单地all(remainder)按照@ShadowRanger 的建议进行操作。i = 3primes = [2]remainder = []while i <= 20:&nbsp; &nbsp; for x in primes:&nbsp; &nbsp; &nbsp; &nbsp; remainder.append(i%x)&nbsp; &nbsp; if all(remainder) == True:&nbsp; &nbsp; &nbsp; &nbsp; primes.append(i)&nbsp; &nbsp; i += 1&nbsp; &nbsp; remainder.clear()print(primes)# [2, 3, 5, 7, 11, 13, 17, 19]评论中再次建议的另一种选择是使用all(rem != 0 for rem in remainder)&nbsp;在那里您对remainder列表中的每个元素使用 for 循环检查。rem != 0根据条件是否满足,会给你真/假。all将简单地检查所有条目是否为 True,在这种情况下,即使单个条目为 False ,它也会返回Trueelse False。如果您想了解all()这里的工作方式,请使用以下输出添加打印语句。如您所见,输出仅False适用于存在单个 0True且不存在 0 的情况。print (remainder, all(remainder))[1] True[0, 1] False[1, 2] True[0, 0, 1] False[1, 1, 2] True[0, 2, 3, 1] False[1, 0, 4, 2] False[0, 1, 0, 3] False[1, 2, 1, 4] True[0, 0, 2, 5, 1] False[1, 1, 3, 6, 2] True[0, 2, 4, 0, 3, 1] False[1, 0, 0, 1, 4, 2] False[0, 1, 1, 2, 5, 3] False[1, 2, 2, 3, 6, 4] True[0, 0, 3, 4, 7, 5, 1] False[1, 1, 4, 5, 8, 6, 2] True[0, 2, 0, 6, 9, 7, 3, 1] False
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python