Created
September 19, 2013 16:50
-
-
Save 89465127/6626311 to your computer and use it in GitHub Desktop.
Find the longest palandrom in a given string, using functional programming and recursion in python.
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
def sliding(iterable, n): | |
return [iterable[i:i+n] for i in range(len(iterable) - n + 1)] | |
def xsliding(iterable, n): | |
for i in range(len(iterable) - n + 1): | |
yield iterable[i:i+n] | |
def reversed_iter(iterable): | |
return iterable[::-1] | |
def find(iterable, f): | |
for i in iterable: | |
if f(i): | |
return i | |
return None | |
def longestPal(s): | |
return longestPalN(s, len(s)) | |
def longestPalN(s, n): | |
found = find(xsliding(s, n), lambda x: x == reversed_iter(x)) | |
if found: | |
return found | |
return longestPalN(s, n-1) | |
s = "a bbb adsf adsfjdsjidk uuuuuiiiiiuuuuu " | |
print longestPal(s) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment