Created
October 8, 2010 21:33
-
-
Save mccutchen/617608 to your computer and use it in GitHub Desktop.
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
| """ | |
| Code for solving the Greplin Challenge | |
| http://challenge.greplin.com/ | |
| """ | |
| from itertools import chain, combinations | |
| # Level one | |
| def palindrome(s): | |
| """Find the largest palindrome in the given string.""" | |
| slen = len(s) | |
| chunks = (s[i:j] for i, c in enumerate(s) for j in xrange(i, slen)) | |
| matches = (a for a in chunks if a == a[::-1]) | |
| return max(matches, key=len) | |
| # Level two | |
| def fibs(): | |
| a, b = 0, 1 | |
| while True: | |
| a, b = b, a + b | |
| yield b | |
| def isprime(n): | |
| for x in xrange(2, int(n ** 0.5) + 1): | |
| if n % x == 0: | |
| return False | |
| return True | |
| def bigprimefib(n): | |
| """Find the first prime number larger than n in the Fibonacci sequence.""" | |
| for x in fibs(): | |
| if x > n and isprime(x): | |
| return x | |
| # (Plus I got the divisors of n+1 from Wolfram Alpha) | |
| # Level three | |
| def subsets(xs): | |
| """Generate a list of subsets of the given list where the largest number | |
| in the subset is the sum of the remaining numbers.""" | |
| pool = chain(*[combinations(xs, i) for i in xrange(3, len(xs))]) | |
| return [ps for ps in pool if sum(ps[:-1]) == ps[-1]] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment