For 循环重复/卡住? Python 3.2
我正在尝试为埃拉托斯特尼筛法编写一个Python脚本。我已经完成了所有操作,但是当我告诉程序测试每个数字是否是 √ 输入下面的至少一个素数的倍数时。它进展顺利,但是当我尝试删除多个时,它会起作用,直到它尝试删除 6 两次为止......我一直在查看我的代码,但似乎找不到原因。我对 Python 相当陌生,所以非常感谢您的帮助! --- 请注意,由于 SOF 制作代码块的方式,我的代码间距已关闭:
import math, os, threading
global iswhole
global tdprime
def iswhole(x):
if x%1 == 0:
return True
else:
return False
def tdprime(x):
prime = True
n = 2
while n < x:
if iswhole(x/n) == True:
return False
prime = False
n = x
else:
n += 1
if prime == True:
return True
number = 0
while number != 1:
number = int(input("Enter number to calculate all primes up to: "))
number_range = range(1,number+1)
sqrt = math.sqrt(number)
rsqrt = round(sqrt)
thelist = []
tsl = []
for num in range(1,rsqrt):
if tdprime(num) == True:
tsl.append(num)
tsl.remove(1)
for x in number_range: ## Making the List
thelist.append(x)
## Note it's " Key: Value " in dictionaries
print(tsl)
print("thelist: ",thelist)
print("Square root of input = ",sqrt)
print("Rounded Square root of input = ",rsqrt)
print()
for x in thelist: ## Testing each number in thelist
multiple = False
for y in tsl: ## Each prime number under √number
if iswhole(x/y):
print(x) ## If the current number in thelist divided by one of the prime numbers under √number is a whole
thelist.remove(x)## Remove the current number which isn't a prime
thelist.sort()
multiple = True ## Make multiple true so it doesn't print (could remove the multiple stuff and other if function, kind of pointless function now)
if multiple == False:
print("Prime! ",x)
print(thelist)
I am trying to write a python script for Sieve of Eratosthenes. I have everything done, but when I tell the program to test each number if it is a multiple of at least one of the prime numbers below the √input. It goes well but when I try to remove a multiple it works until it tries to delete 6 twice... I've been looking over my code and can't seem to find out why. I'm rather new to Python so help would be much appreciated!
--- Note my code's spacing is off due to SOF's way of making code blocks:
import math, os, threading
global iswhole
global tdprime
def iswhole(x):
if x%1 == 0:
return True
else:
return False
def tdprime(x):
prime = True
n = 2
while n < x:
if iswhole(x/n) == True:
return False
prime = False
n = x
else:
n += 1
if prime == True:
return True
number = 0
while number != 1:
number = int(input("Enter number to calculate all primes up to: "))
number_range = range(1,number+1)
sqrt = math.sqrt(number)
rsqrt = round(sqrt)
thelist = []
tsl = []
for num in range(1,rsqrt):
if tdprime(num) == True:
tsl.append(num)
tsl.remove(1)
for x in number_range: ## Making the List
thelist.append(x)
## Note it's " Key: Value " in dictionaries
print(tsl)
print("thelist: ",thelist)
print("Square root of input = ",sqrt)
print("Rounded Square root of input = ",rsqrt)
print()
for x in thelist: ## Testing each number in thelist
multiple = False
for y in tsl: ## Each prime number under √number
if iswhole(x/y):
print(x) ## If the current number in thelist divided by one of the prime numbers under √number is a whole
thelist.remove(x)## Remove the current number which isn't a prime
thelist.sort()
multiple = True ## Make multiple true so it doesn't print (could remove the multiple stuff and other if function, kind of pointless function now)
if multiple == False:
print("Prime! ",x)
print(thelist)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
通过以下实现可以大大简化您的代码:
可以根据需要轻松生成最多为 n 的数字,而不必预先计算它们并将其存储在列表中。
2 是唯一的偶素数,因此只需测试奇数。
所有数字都可以唯一地完全分解为质因数(这称为算术基本定理)。这意味着您需要尝试除以的唯一数字是您之前计算过的素数——无论如何,所有其他数字都将至少能被这些素数之一整除(或者它们本身就是素数)。
尝试按照以下方式进行操作:
另外,请注意间距和缩进。在 Python 中,当间距错误时,不仅难以阅读,而且还会出现运行时错误。
Your code can be much simplified by the following realisations:
The numbers up to a number n can easily be generated as needed, they don't have to be calculated berforehand and stored in a list.
2 is the only even prime, so you only need to test odd numbers.
All numbers can be fully factorised into prime factors, uniquely (this is called the fundamental theorem of arithmetic). This means that the only numbers which you need to try dividing by are the primes you have previously calculated --- all other numbers will be divisible by at least one of those primes anyway (or they would be primes themselves).
Try something along these lines:
Also, please pay attention to spacing and indentation. In Python, when you get your spacing wrong it is not only difficult to read, but a runtime error.
我有点担心你的 iswhole() 函数:(
顺便说一下,这可以简单地重写为 return (x%1 == 0) 并跳过
return True
和return False
部分。)浮点数是奇怪的生物:
对于像
6
这样的输入,这似乎不太可能是问题,但也可能成为问题对于更大的输入。 比较浮点数很麻烦。对于
6
问题,我建议您可能希望使用数组,而不是使用可变列表来跟踪数据。数组永远不需要排序(程序中有sort()
的事实有点像试图掩盖某种错误)并删除元素从列表中间开始的操作通常非常昂贵。 (sort
几乎意味着您的性能无论如何都会很差。对于小输入来说没什么大不了的,但尝试以 1000000 作为起点。)将数组中的元素设置为1< /code> 或
0
几乎总是比可变列表便宜得多。I'm a little worried about your
iswhole()
function:(Incidentally, this could be re-written as simply
return (x%1 == 0)
and skip thereturn True
andreturn False
pieces.)Floating point numbers are odd creatures:
For an input such as
6
, this doesn't seem likely to be the problem, but it might become a problem for larger inputs. Comparing floating point numbers is troublesome.For the
6
problem, I'd like to suggest that instead of a mutable list to keep track of your data, you might wish to use an array instead. The array never needs to be sorted (the fact that you have asort()
in your program smells a bit like trying to paper over some kind of bug) and deleting elements from the middles of lists is often extremely expensive. (Thatsort
pretty much means your performance is going to be poor anyhow. Not a big deal for small inputs, but try 1000000 as a starting point.) Setting elements in an array to1
or0
is almost always far cheaper than mutable lists.我发现这方面有一个问题:
您在迭代
thelist
时调用thelist.remove(x)
和thelist.sort()
。您通常不想修改在 Python 中迭代的结构。它通常会混淆进行迭代的内部机制;你会出现一些症状,例如神秘地跳过元素或处理它们两次,或其他奇怪的现象。I see a problem with this bit:
You call
thelist.remove(x)
andthelist.sort()
while iterating overthelist
. You generally don't want to modify a structure you're iterating over in Python. It usually confuses the internal machinery doing the iteration; you get symptoms like mysteriously skipping elements or processing them twice, or other weirdness.