Python生成给定푛以内素数列表时出现TypeError: the range object is not callable错误的求助
Hey there! Let's work through this problem together.
First, let's address that TypeError: the range object is not callable error. Your provided code doesn't explicitly overwrite the built-in range function, but this error almost always pops up if somewhere in your Python session (like in the interactive shell or other code you ran before this snippet) you accidentally assigned a value to range—for example, typing something like range = [1,2,3] would turn the range function into a list, making it impossible to call. If that's the case, restarting your Python interpreter should clear up the immediate error.
But even after fixing that, your prime generation logic has some inefficiencies and minor issues. Let's refactor it to use the Sieve of Eratosthenes, the standard efficient method for generating primes up to a given number:
修正后的优化代码
def prime_list(n): if n < 2: return [] # 初始化筛子:默认所有数都是素数 sieve = [True] * (n + 1) sieve[0] = sieve[1] = False # 0和1不是素数 # 遍历到n的平方根即可(更大的因数必然对应一个更小的因数) for current in range(2, int(n ** 0.5) + 1): if sieve[current]: # 如果当前数是素数,标记它的所有倍数为非素数 sieve[current*current : n+1 : current] = [False] * len(sieve[current*current : n+1 : current]) # 收集所有仍被标记为素数的数字 primes = [num for num, is_prime in enumerate(sieve) if is_prime] return primes my_prime = prime_list(100) print(my_prime)
为什么你的原始代码需要调整?
- 效率低下:你的嵌套循环会生成大量重复的非素数(比如6会通过23和32两次被加入
non列表),再转成集合去重,当n较大时会变得非常慢。 - 逻辑冗余:把1加入
non列表再筛选的操作完全没必要——1本身就不是素数,可以直接提前排除。 - 隐性错误风险:如果你的环境里
range被意外覆盖,就会触发那个可调用对象错误。重启解释器可以避免,但平时要注意不要用内置函数名给变量命名!
测试修正后的代码
运行这段代码,输入n=100会输出100以内的所有素数:
[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]
内容的提问来源于stack exchange,提问作者Raha Moosavi

