Created
January 25, 2016 19:31
-
-
Save RyanMarcus/3978c3a1bad007f585a7 to your computer and use it in GitHub Desktop.
This file contains 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
# find a palindrome in just two (reasonable) or one unreasonable line of Python code | |
# Copyright Ryan Marcus and Can Nahum 2016 | |
import collections | |
import functools | |
def getPalin(x): | |
m = functools.reduce(lambda d,c: {k: v if k != c else v + 1 for (k, v) in d.items()}, # folds new value into dictionary | |
x, # for each character in the string | |
{k: 0 for (v,k) in enumerate(x)}) # start with all values = 0 | |
return (("".join([k*(int(v/2)) for (k, v) in m.items() if v % 2 == 0]) + | |
"".join([k*v for (k, v) in m.items() if v % 2 == 1]) + | |
"".join([k*(int(v/2)) for (k, v) in m.items() if v % 2 == 0])[::-1]) | |
if len({k: v for (k, v) in m.items() if v % 2 == 1}) <= 1 else -1) | |
if __name__ == "__main__": | |
x = "bbccffggh" | |
print(getPalin(x)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment