2011-01-06 4 views
0
#!/usr/bin/python 
# 
# Description: bitwise factorization and then trying to find 
# an elegant way to print numbers 

# Source: http://forums.xkcd.com/viewtopic.php?f=11&t=61300#p2195422 
# bug with large numbers such as 99, but main point in simplifying it 
# 
def primes(n): 
    # all even numbers greater than 2 are not prime. 
    s = [False]*2 + [True]*2 + [False,True]*((n-4)//2) + [False]*(n%2) 
    i = 3; 
    while i*i < n: 
     # get rid of ** and skip even numbers. 
     s[i*i : n : i*2] = [False]*(1+(n-i*i)//(i*2)) 
     i += 2 
     # skip non-primes 
     while not s[i]: i += 2 
    return s 


# TRIAL: can you find a simpler way to print them? 
# feeling the overuse of assignments but cannot see a way to get it simpler 
# 
p = 49 
boolPrimes = primes(p) 
numbs = range(len(boolPrimes)) 
mydict = dict(zip(numbs, boolPrimes)) 

print([numb for numb in numbs if mydict[numb]]) 

私が探しているものは、TRIALを以下のように極端に簡潔にすることができますか?そのような方法は?範囲(n)とブール値リスト、1対1マップの解釈は簡単ですか?

a=[True, False, True] 
b=[1,2,3] 
b_a     # any such simple way to get it evaluated to [1,3] 
         # above a crude way to do it in TRIAL 

答えて

2

、あなたは、例えば

>>> from itertools import compress 
>>> a=[True, False, True] 
>>> b=[1,2,3] 
>>> list(compress(b,a)) 
[1, 3] 

itertools.compress

itertools.compress(b,a) 

を使用することができそうでなければ、リストの内包に

を使用することができますあなたが素数のリストにこれをしたい場合は

、列挙を使用する方が簡単かもしれ

>>> primes = [False, False, True, True, False, True] 
>>> list(compress(*zip(*enumerate(primes)))) 
[2, 3, 5] 
0

あなたは非常にこのにそれを簡素化するために、リスト内包表記と一緒にenumerateを使用することができます。dictsが順序付けられていないので、ここで辞書を作る

p = 49 
print([num for num, isprime in enumerate(primes(p)) if isprime]) 
0

は、あなたがとにかく欲しいものではありません。ペアをペアとして保つことは、実際にはペアを反復し、2つの要素名を与え、それらの名前を理解に使用できるので、ロジックを単純化します。

インデックスの並行リストを使用してリストを '圧縮'するには、enumerateを使用します。したがって

:python2.7の+の場合

print ([x for (x, y) in enumerate(primes(49)) if y]) 
関連する問題