Created
February 18, 2016 04:48
-
-
Save anonymous/87c3c4aa2eafbd74cb75 to your computer and use it in GitHub Desktop.
palindrome
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
s = 'xyabax' | |
d0 = dict() | |
d1 = dict() | |
def calc0(s): | |
global inf | |
inf = len(s) + 1 | |
return calc(s) | |
def calc(s): | |
if len(s) == 0: | |
return 0, 0 | |
if len(s) == 1: | |
return 1, 1 | |
if s in d0: | |
return d0[s], d1[s] | |
else: | |
if s[0] == s[-1]: | |
d1[s] = calc(s[1:-1])[0] | |
else: | |
d1[s] = inf | |
candidates = [(calc(s[0:i])[0] + calc(s[i:])[0]) for i in range(1, len(s))] | |
candidates.append(d1[s]) | |
#print s, candidates | |
d0[s] = min(candidates) | |
return d0[s], d1[s] | |
print calc0('xyabax') | |
print calc0('caacadac') | |
print calc0('zabaefeghgpz') | |
print calc0('zabaxcdcyefexghgz') | |
print calc0('abacdc') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment