Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/google-sheets/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
为什么';而';使程序在Python中运行更长时间_Python_Python 3.6 - Fatal编程技术网

为什么';而';使程序在Python中运行更长时间

为什么';而';使程序在Python中运行更长时间,python,python-3.6,Python,Python 3.6,我写了一个程序来找出数字列表中的素数,只是为了练习格式化等等。这是我的密码: from math import * #Defining range to be checked a = range(1,10) #Opening empty list b = [] #Wilsons method for primes for n in a: if ((factorial(n-1))+1)%n == 0: b.append(n) 这段代码运行起来没有问题,速度相当快,至少在这

我写了一个程序来找出数字列表中的素数,只是为了练习格式化等等。这是我的密码:

from math import *
#Defining range to be checked
a = range(1,10)
#Opening empty list
b = []
#Wilsons method for primes
for n in a:
    if ((factorial(n-1))+1)%n == 0:
        b.append(n)
这段代码运行起来没有问题,速度相当快,至少在这个使用阶段是如此。但是,当我包含while语句(见下文)时,它的速度要慢得多

from math import *
#Defining range to be checked
a = range(1,10)
#Opening empty list
b = []
#Wilson't method for primes
for n in a:
    while n>1:
        if ((factorial(n-1))+1)%n == 0:
            b.append(n)
谁能解释一下为什么会这样

n、 我知道有更有效的方法来寻找素数。我只是在练习格式化等等,尽管我不介意改进我的代码


编辑:错误添加小于符号,而不是适当的大于符号。更正。

正如一些人指出的那样,您的代码将导致无限循环,因为
n
的值在您的
循环中不变

首先,您可能不是在寻找
while
循环。在没有第一次迭代(n=1)的情况下,使用
for
循环就足够了。如果坚持包含n=1,则使用
If
语句是一种可能的解决方法:

a=range(1,10)
b=[]
for n in a:
    if n>1:
        if ((factorial(n-1))+1)%n == 0:
            b.append(n)

第二个代码应该快得多,因为
n
1
开始,因此永远不会满足
n
,而我认为根本不需要while循环,只要你不更改(减少)while循环中
n
的值,循环条件就会始终满足,从而导致无限长的循环。如何?像永远?因为现在这里有一个无限循环。n在循环中从不改变。