我刚才碰到这个(真的)简单的程序。它只输出第一个x素数。我不好意思问,有没有办法使它更“蟒蛇式”的(即浓缩它,同时使它(更)可读?切换函数很好;我只对可读性感兴趣。
谢谢
from math import sqrt
def isprime(n):
if n ==2:
return True
if n % 2 ==0 : # evens
return False
max = int(sqrt(n))+1 #only need to search up to sqrt n
i=3
while i <= max: # range starts with 3 and for odd i
if n % i == 0:
return False
i+=2
return True
reqprimes = int(input('how many primes: '))
primessofar = 0
currentnumber = 2
while primessofar < reqprimes:
result = isprime(currentnumber)
if result:
primessofar+=1
print currentnumber
#print '\n'
currentnumber += 1
最佳答案
你的算法本身可能是通过pythonic实现的,但是以函数的方式重新编写算法通常是有用的——你可能最终得到一个完全不同但更具可读性的解决方案(甚至更像pythonic)。
def primes(upper):
n = 2; found = []
while n < upper:
# If a number is not divisble through all preceding primes, it's prime
if all(n % div != 0 for div in found):
yield n
found.append( n )
n += 1
用法:
for pr in primes(1000):
print pr
或者,考虑到阿拉斯代尔的评论,一个更有效的版本:
from math import sqrt
from itertools import takewhile
def primes(upper):
n = 2; foundPrimes = []
while n < upper:
sqrtN = int(sqrt(n))
# If a number n is not divisble through all preceding primes up to sqrt(n), it's prime
if all(n % div != 0 for div in takewhile(lambda div: div <= sqrtN, foundPrimes)):
yield n
foundPrimes.append(n)
n += 1
关于python - 可以将其设置为更多pythonic吗?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/1775459/