DEV Community

Discussion on: Write a script to find permutable prime numbers

Collapse
 
dwd profile image
Dave Cridland

So this doesn't sort... But on the other hand it uses recursive generators, so that has to be a good thing, right?

def perm(l):
    if 1 == len(l):
        yield l[0]
        return
    for i in range(len(l)):
        ll = []
        for j in range(len(l)):
            if j != i:
                ll.append(l[j])
        for p in perm(ll):
            yield l[i] + p
    return

def perms(x):
    l = [ c for c in str(x) ]
    p = [ str(x) ]
    for pp in perm(l):
        yield int(pp)
    return

def primes(r):
    pr = [2]
    yield 2
    for p in range(3, r + 1):
        if p not in pr:
            for n in pr:
                if p % n == 0:
                    break
            else:
                pr.append(p)
                t = []
                for n in perms(p):
                    if n in t:
                        continue
                    if n not in pr:
                        break
                    else:
                        t.append(n)
                else:
                    for n in t:
                        yield n

print [i for i in primes(1000)]