Created
May 18, 2012 05:21
-
-
Save r3/2723315 to your computer and use it in GitHub Desktop.
Project Euler Challenge 7
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"""You'll have to forgive me some of the ugly, | |
I wrote this when I was new to Python, but it looks passable. | |
-r3 | |
""" | |
def is_prime(num): | |
"""Checks argument for primality""" | |
# Optimization to determine if even | |
if num % 2 == 0: | |
return False | |
# From there on out, we can just check odds | |
div = 3 | |
while div <= (num * num): | |
if not num % div: | |
return False | |
div += 2 | |
return True | |
def prime_gen(start=2): | |
"""Produces prime numbers | |
Returns an iterable generator for | |
consecutive increasing primes | |
starting with the optional argument. | |
Default start is 2, the lowest prime. | |
""" | |
# Again, checking for evens first | |
if start == 2: | |
# Notice the multiple yeild statements here? | |
# Execution will "pause" on each, yielding the value and "continue" | |
# execution when asked for the next prime | |
yield 2 | |
yield 3 | |
start += 3 | |
# Moving on to the heart of the matter... Checking odds. | |
while True: | |
if is_prime(start): | |
yield start | |
elif start % 2 == 0: | |
start += 1 | |
start += 2 | |
if __name__ == '__main__': | |
# `enumerate` is one you may not have seen before; it turns each value in an | |
# iterable into a tuple pair: (0, n), (1, n+1), (2, n+2), (3, n+3) ... | |
# The leading value in the pair is the index with the usual return value of the | |
# iterable as 'n'. This allows us to check if the count (index + 1) has reached our | |
# desired prime. The `enumerate` gets rid of the ugly but common idiom: | |
# for ix in range(len(var)) => for ix, _ in enumerate(var) | |
# Note that the '_' character is idiomatic for vars that you'll not be using and is | |
# otherwise a valid variable. | |
for count, prime in enumerate(prime_gen()): | |
if count + 1 == 10001: | |
print prime | |
break |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment