[英]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習語和語言功能:
if __name__ == '__main__': ...
[4]。 [1] http://www.ibm.com/developerworks/library/l-pycon/index.html
[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.