我得到了一个数字(n),以及该数字可能的除数的数组。我应该以相反的顺序返回范围(n)的所有可能质数的列表,并且必须通过list-comprehension将其写在一行中。
我用一行写的东西可以得到必要的输出,但是我不知道如何将它写成列表理解。
除数:
DOUBLE = 2
divisors = [i for i in range(DOUBLE, math.ceil(n/DOUBLE))]
non_primes = []
for item in divisors:
for item2 in divisors:
non_primes += [item*item2]
这是我的代码:
return list(set(range(2, n)) - set(non_primes))[::-1]
这是问题附带的文档字符串:
"""
Given a number and an array of possible divisors,
return a list of all the primes in the same range in
reverse order.
Use list comprehension in a single line.
:param n: a non-negative integer
:returns: a list of prime numbers
:Example:
>>> primes(10)
[7, 5, 3, 2]
"""
答案 0 :(得分:2)
您可以使用列表推导,以相反的顺序将整数从n
迭代到2
,并仅保留给定除数之一或者不能被除数之一除的整数。除数:
[i for i in range(n, 1, -1) if i in divisors or all(i % d for d in divisors)]
答案 1 :(得分:0)
这应该做到。
import math
n = 100
DOUBLE = 2
divisors = [i for i in range(DOUBLE, math.ceil(n/DOUBLE))]
#Get primes
print(list(set(range(2, n)) - set([ item*item2 for item in divisors for item2 in divisors]))[::-1])
#[97, 89, 83, 79, 73, 71, 67, 61, 59, 53, 47, 43, 41, 37, 31, 29, 23, 19, 17, 13, 11, 7, 5, 3, 2]
for循环
for item in divisors:
for item2 in divisors:
non_primes += [item*item2]
转换为
[ item*item2 for item in divisors for item2 in divisors]
也如注释中所建议,您可以通过使用itertools.product来简化double for循环,如下所示。
import math
import itertools
n = 100
DOUBLE = 2
divisors = [i for i in range(DOUBLE, math.ceil(n/DOUBLE))]
#Find all combinations of divisors
prod = itertools.product(divisors, repeat=2)
#Run through all combinations to get non primes
non_primes = [t[0]*t[1] for t in prod]
#Get primes
print([item for item in list(range(2, n)) if item not in non_primes][::-1])
除了设置差异之外,您还可以这样做
import math
import itertools
n = 100
DOUBLE = 2
divisors = [i for i in range(DOUBLE, math.ceil(n/DOUBLE))]
#Find all combinations of divisors
prod = itertools.product(divisors, repeat=2)
#Run through all combinations to get non primes
non_primes = [t[0]*t[1] for t in prod]
#Get primes
print([item for item in list(range(2, n)) if item not in non_primes][::-1])
答案 2 :(得分:0)
我的建议是将其真正整合为单线。
代码
def getReversedPrimes(n):
return sorted(set(range(2, n)) - set([k*l for k in range(2, int(n/2)) for l in range(2, int(n/2))]), reverse=True)
print(getReversedPrimes(10))
print(getReversedPrimes(100))
输出
[7, 5, 3, 2]
[97, 89, 83, 79, 73, 71, 67, 61, 59, 53, 47, 43, 41, 37, 31, 29, 23, 19, 17, 13, 11, 7, 5, 3, 2]
说明
range
返回一个生成器对象,可以将其用于迭代。sorted
的内置函数reversed
确保输出的顺序相反。 set
不一定要排序。顺便说一句,在集上使用减法从第一个集中删除元素的妙法。