我今天是从官网的教程开始学习python的。
当阅读有关filter(function, sequence) 的内容时,我想制作一个函数,如果数字是质数则返回,以便与过滤器一起使用。
notDividedBy = [2,3,4,5,6,7,8,9]
def prime(num):
"""True if num is prime, false otherwise"""
copy = notDividedBy[:]
check = True
if num in copy:
copy.remove(num)
for x in copy:
if num % x == 0:
check = False
break
return check
以上代码在 shell 中有效。
我的问题是:因为我觉得虽然是一个解决方案,但它不是最优雅的,任何人都可以将这段代码转换成更像 python 的东西吗?(更好的结构?更少的行?)
我相信它会帮助我更好地理解这门语言的基础知识。
问题是,不要使用任何进口或任何东西,只使用简单的员工。
请您参考如下方法:
创建许多列表的副本并不是一种特别有效的做事方式。而是使用 xrange() (Python 2.x) 或 range() (Python 3) 迭代器。这是您可以实现素性测试的一种(天真)方法:
from math import sqrt
def isPrime(n):
if n < 2: return False
if n == 2: return True
if not n % 2: return False #test if n is even
#we've already remove all the even numbers, no need to test for 2
#we only need to test up to sqrt(n), because any composite numbers can be
# factored into 2 values, at least one of which is < sqrt(n)
for i in xrange(3, int(sqrt(n)) + 1, 2):
if not n % i:
return False
return True
