For 循环重复/卡住? Python 3.2

发布于 2024-12-21 02:41:28 字数 1707 浏览 1 评论 0原文

我正在尝试为埃拉托斯特尼筛法编写一个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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

独孤求败 2024-12-28 02:41:28

通过以下实现可以大大简化您的代码:

  • 可以根据需要轻松生成最多为 n 的数字,而不必预先计算它们并将其存储在列表中。

  • 2 是唯一的偶素数,因此只需测试奇数。

  • 所有数字都可以唯一地完全分解为质因数(这称为算术基本定理)。这意味着您需要尝试除以的唯一数字是您之前计算过的素数——无论如何,所有其他数字都将至少能被这些素数之一整除(或者它们本身就是素数)。

尝试按照以下方式进行操作:

stop = int(input("Enter number to calculate all primes up to: "))

primes = []

for n in range(3, stop, 2): # Step by two each time
    was_prime = True # Needed to break out of nested loop
    for p in primes:
        if n % p == 0: # A prime divides n
             was_prime = False
             break # No need to continue
    if was_prime:
        primes.append(n)

print(primes) # You can insert the number 2 here if you like

另外,请注意间距和缩进。在 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:

stop = int(input("Enter number to calculate all primes up to: "))

primes = []

for n in range(3, stop, 2): # Step by two each time
    was_prime = True # Needed to break out of nested loop
    for p in primes:
        if n % p == 0: # A prime divides n
             was_prime = False
             break # No need to continue
    if was_prime:
        primes.append(n)

print(primes) # You can insert the number 2 here if you like

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.

夏花。依旧 2024-12-28 02:41:28

我有点担心你的 iswhole() 函数:(

def iswhole(x):
    if x%1 == 0:
        return True
    else:
        return False

顺便说一下,这可以简单地重写为 return (x%1 == 0) 并跳过return Truereturn False 部分。)

浮点数是奇怪的生物:

>>> 10.0%1
0.0
>>> (10.1 * 10)%1
0.0
>>> (10.01 * 100)%1
0.0
>>> (10.001 * 1000)%1
0.0
>>> (10.0001 * 10000)%1
0.0
>>> (10.00001 * 100000)%1
0.0
>>> (10.000001 * 1000000)%1
0.0
>>> (10.0000001 * 10000000)%1
0.0
>>> (10.00000001 * 100000000)%1
1.1920928955078125e-07

对于像 6 这样的输入,这似乎不太可能是问题,但也可能成为问题对于更大的输入。 比较浮点数很麻烦

对于 6 问题,我建议您可能希望使用数组,而不是使用可变列表来跟踪数据。数组永远不需要排序(程序中有 sort() 的事实有点像试图掩盖某种错误)并删除元素从列表中间开始的操作通常非常昂贵。 (sort 几乎意味着您的性能无论如何都会很差。对于小输入来说没什么大不了的,但尝试以 1000000 作为起点。)将数组中的元素设置为 1< /code> 或 0 几乎总是比可变列表便宜得多。

I'm a little worried about your iswhole() function:

def iswhole(x):
    if x%1 == 0:
        return True
    else:
        return False

(Incidentally, this could be re-written as simply return (x%1 == 0) and skip the return True and return False pieces.)

Floating point numbers are odd creatures:

>>> 10.0%1
0.0
>>> (10.1 * 10)%1
0.0
>>> (10.01 * 100)%1
0.0
>>> (10.001 * 1000)%1
0.0
>>> (10.0001 * 10000)%1
0.0
>>> (10.00001 * 100000)%1
0.0
>>> (10.000001 * 1000000)%1
0.0
>>> (10.0000001 * 10000000)%1
0.0
>>> (10.00000001 * 100000000)%1
1.1920928955078125e-07

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 a sort() 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. (That sort 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 to 1 or 0 is almost always far cheaper than mutable lists.

你在我安 2024-12-28 02:41:28

我发现这方面有一个问题:

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()

您在迭代 thelist 时调用 thelist.remove(x)thelist.sort()。您通常不想修改在 Python 中迭代的结构。它通常会混淆进行迭代的内部机制;你会出现一些症状,例如神秘地跳过元素或处理它们两次,或其他奇怪的现象。

I see a problem with this bit:

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()

You call thelist.remove(x) and thelist.sort() while iterating over thelist. 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文