Interpretation of range(n) and boolean list, one-to-one map, simpler?

Posted by HH on Stack Overflow See other posts from Stack Overflow or by HH
Published on 2011-01-06T02:10:40Z Indexed on 2011/01/06 2:54 UTC
Read the original article Hit count: 157

Filed under:
|
#!/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]])

Something I am looking for, can you get TRIAL to be of the extreme simplicity below? Any such method?

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

© Stack Overflow or respective owner

Related posts about python

Related posts about assignment