Eratosthenes-紧凑的Python Python-筛 [英] Python- Sieve of Eratosthenes- Compact Python
问题描述
这是我的code查找使用埃拉托色尼的筛素数。
名单= [我为我的range(2,INT(进行raw_input(计算素数到什么号码?))+ 1)]
因为我在名单:
对于在列表:
如果A = I和%I == 0!
list.remove(一)
试图找到一种方法,COM preSS这些嵌套的循环变成某种发生器或COM prehension,但它似乎并不认为你可以使用一个COM $ P函数应用到列表$ phension。我尝试使用地图和过滤器,但我似乎无法得到它的权利。
思考是这样的:
打印地图(list.remove(一),过滤器(拉姆达一,我:(A I == 0和= I),[(A,I)为%我在列表中的一个列表])
显然不能一打理由工作。如果我只是使用了code中的过滤器部分:
过滤器(拉姆达一,我:(1%我== 0和= 1),** [在列表中的列表(A,I)对我的]! **
什么是把两个变量进入拉姆达的正确方法是什么? (A,I),使其成为一个元组,但我想提出'a'和'我'为自变量,以投入的lambda。
我结束了解决这一个班轮问题:
打印排序(集([我为我的range(2,INT(进行raw_input(计算素数到什么号码?))+ 1)]),差(一因为我在l对于在l如果!=我和%I == 0))
这不是precisely直接翻译你的循环,但是它是相当密切的,紧凑的:
>>>升=范围(2,101)
>>>排序(集(L).difference(一个为我在l对于在l如果!=我和%I == 0))
[2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97 ]
虽然我会建议 A>我
,而不是 A = 0
作为短,速度更快;!)
This is my code for finding primes using the Sieve of Eratosthenes.
list = [i for i in range(2, int(raw_input("Compute primes up to what number? "))+1)]
for i in list:
for a in list:
if a!=i and a%i == 0:
list.remove(a)
Trying to find a way to compress those nested for loops into some kind of generator or comprehension, but it doesn't seem that you can apply a function to a list using a comprehension. I tried using map and filter, but I can't seem to get it right.
Thinking about something like this:
print map(list.remove(a), filter(lambda a, i: (a%i ==0 and a!=i), [(a, i) for i in list for a in list])
Obviously doesn't work for a dozen reasons. If I just was using the filter portion of that code:
filter(lambda a, i: (a%i ==0 and a!=i), **[(a, i) for i in list for a in list]**
What's the proper way of putting two variables into the lambda? (a,i) makes it a tuple, but I want to submit 'a' and 'i' as independent variables to put into the lambda.
I ended up resolving the problem with this one-liner:
print sorted(set([i for i in range(2, int(raw_input("Compute primes up to what number? "))+1)]).difference(a for i in l for a in l if a!=i and a%i == 0))
It's not precisely a direct translation of your loops, but it's quite close and compact:
>>> l = range(2, 101)
>>> sorted(set(l).difference(a for i in l for a in l if a!=i and a%i == 0))
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
Although I'd suggest a > i
rather than a != 0
as being shorter and faster ;)
这篇关于Eratosthenes-紧凑的Python Python-筛的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!