2
\$\begingroup\$

I'm back with a Python solution for Project Euler 35. Any help would be appreciated; I generate the numbers by observing that all circular primes can only have digits 1, 3, 7, and 9. Then I use the Cartesian product built into itertools. I also have a local primes test from Wikipedia.

from primes import test as is_prime
from itertools import product # cartesian product
from timeit import default_timer as timer

def find_circular_primes_under(limit):
    def is_circular(digits):
        digits = list(digits)
        for digit in digits:
            if not is_prime(int(''.join(map(str, digits)))):
                return False
            else:
                digits.append(digits.pop(0))
        return True

    if type(limit) != int or limit <= 2:
        return "Error: primes are positive integers greater than 1."
    elif limit <= 11:
        sum = 0
        for k in range(limit):
            if is_prime(k):
                sum += 1
        return sum

    else:
        sum = 4
        for k in range(2, len(str(limit))):
            for combo in product([1, 3, 7, 9], repeat = k):
                if is_circular(combo):
                    sum += 1
        return sum

start = timer()
ans = find_circular_primes_under(10**6)
elapsed_time = (timer() - start) * 1000 # s --> ms

print "Found %d in %r ms." % (ans, elapsed_time)
\$\endgroup\$

1 Answer 1

4
\$\begingroup\$
  • Returning an error message instead of data is not a good approach to handling errors. Try and see what happens if you tweak your code to pass an invalid argument to find_circular_primes_under. Do you see your error message? No, the program raises an exception trying to format the return value as a number. It would be better to raise an appropriate exception instead of returning from the function.
  • Modifying a container while iterating over it causes undefined behavior. In is_circular you could use for _ in xrange(len(digits)): instead of for digit in digits: to be safe. The digit variable is not used anyway.
  • You could take advantage of collections.deque and its rotate method to produce the rotations.
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.