繁体   English   中英

循环中的Python Print语句,生成素数

[英]Python Print statement in a loop, generating prime numbers

我可以在哪里放置打印语句以打印最终列表,但仍保留返回值,您有什么方法可以改进此功能。 我写了函数,但是不确定它的相对质量

def buildPrimeList ():

    primeList = [1, 2]
    possiblePrime = 3
    print "To display all prime values less than or equal a number..."
    x = raw_input("Enter a number higher then 3   ")
    while (possiblePrime <= x):  
        divisor = 2
        isPrime = True

    while (divisor < possiblePrime and isPrime):
        if (possiblePrime % divisor == 0):
            isPrime = False
        divisor = divisor + 1

    if (isPrime):
        primeList.append(possiblePrime)

    possiblePrime = possiblePrime + 2

  return primeList


buildPrimeList() 

打印函数结果非常简单:

print buildPrimeList()

我也注意到您没有将raw_input的结果(字符串)转换为int:

x = int(raw_input("Enter a number higher then 3   "))

在python中执行相同操作的另一种方法可能类似于:

from itertools import count

def is_prime(n):
    """Checks if given number 
    n is prime or not."""

    for i in xrange(2, n/2):
        if n % i == 0:
            return False
    else:
        return True

def prime_numbers():    
    """Generator function which lazily
    yields prime numbers one by one."""

    for i in count(1):
        if is_prime(i):
            yield i

if __name__ == '__main__':

    maxprime = int(raw_input("Enter a number:"))

    for prime in prime_numbers():
        if prime < maxprime:
            print prime
        else:
            break

使用了许多python习语和语言功能:

  • 生成器函数和迭代器[1];
  • snake_case_method_naming [2];
  • docstrings [3];
  • if __name__ == '__main__': ... [4]。

[1] http://www.ibm.com/developerworks/library/l-pycon/index.html

[2] PEP 8:Python代码样式指南

[3] http://www.learningpython.com/2010/01/08/introducing-docstrings/

[4] 如果__name__ ==“ __main__”:该怎么办?


ps正如豆形软糖和rpInt在回答和评论中指出的那样,有许多方法可以加快处理速度。 但是很可能您不应该这样做(除非绝对必要),因为“简单胜于复杂” [5]。

[5] PEP 20:Python的禅宗

您可以在返回之前立即print列表。

至于算法的效率,请考虑使用erathostenes筛子

您只需将每个第二个数字除以它就可以大大改善该功能。 首先,1不是素数,您不应以这种方式使用它。 其原因是质数分解,它对于每个数字都是唯一的,例如9 = 3 * 3。 如果将1加到主池中,则9 = 3 * 3,9 = 3 * 3 * 1,9 = 3 * 3 * 1 * 1,每个都是有效的质因数分解,但对于每个数字。 其次,您不必检查每个自然数。 如果您考虑自然数,则它们的每一秒都是偶数且可被2除。因此,如果数字可被4除,则按定义将其除以2。您可以将计算量减少一个如果使用此属性,则系数为2。 另外,您似乎使用了一种称为“ Erastothenes筛子”的技术http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes ,它只是将质数添加到池中,并检查下一个自然数是否可除。 您可以轻松地利用它。

def buildPrimeList ():
    #One is not really a prime, so we cut it out.
    primeList = [2]
    possiblePrime = 3
    print "To display all prime values less than or equal a number..."
    upperlimit = raw_input("Enter a number higher then 3   ")
    try:
        upperlimit = int(upperlimit)
    except:
        print "Sorry. You didn't enter a number."
        return
    while (possiblePrime <= upperlimit):  
        #lets check if the possible prime is divisable by any prime we already know.
        isPrime = True
        for prime in primeList:
            if(possiblePrime % prime == 0):
                #we can abort the check here, since we know already that this number can't be a prime
                isPrime = False
                break

        if (isPrime):
            primeList.append(possiblePrime)

        possiblePrime = possiblePrime + 2

    return primeList


print buildPrimeList() 

这应该按预期工作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM