Skip to content

Instantly share code, notes, and snippets.

@89465127
Created September 19, 2013 16:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 89465127/6626311 to your computer and use it in GitHub Desktop.
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.
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