Problem 35 of Project Euler is as so:
The number, 197, is called a circular prime because all rotations of the digits: 197, 971, and 719, are themselves prime.
There are thirteen such primes below 100: 2, 3, 5, 7, 11, 13, 17, 31, 37, 71, 73, 79, and 97.
How many circular primes are there below one million?
My, rather crude, approach is to first generate all the primes below one million then filter out all the primes which contain even digits or the number 5 (as there will always be a non-prime permutation). Then, for each element in this reduced list of primes to return all the possible permutations of the number using the permutations() function in the itertools module, then to check if any of these permutations are not prime and if so to remove the element from the list of primes.
from itertools import permutations
def gen_primes(limit):
D = {}
q = 2
while q <= limit:
if q not in D:
yield q
D[q * q] = [q]
else:
for p in D[q]:
D.setdefault(p + q, []).append(p)
del D[q]
q += 1
def odd_primes(limit):
r = list(gen_primes(limit))
for i in r[:]:
for j in str(i):
if any(int(j)%2 == 0 or int(j) == 5 for j in str(i)):
r.remove(i)
break
r.extend([2,5])
return r
def circular_list():
prime_list = odd_primes(1000000)
for i in prime_list[:]:
perm = [''.join(j) for j in permutations(str(i))]
if any(int(j) not in prime_list for j in perm):
prime_list.remove(i)
break
return prime_list
print len(circular_list)
The output yields a value which is incorrect by some margin. I've really been struggling to find the mistake in either the logic or code (or both). Is the permutations() function a viable approach?
I understand that there are more efficient approaches, but I'd be grateful if someone could point me in a direction to make this one work.