Skip to content

Instantly share code, notes, and snippets.

@msyvr
Last active October 26, 2021 23:45
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 msyvr/2f4645f395d7fcecb3835267e3a9750e to your computer and use it in GitHub Desktop.
Save msyvr/2f4645f395d7fcecb3835267e3a9750e to your computer and use it in GitHub Desktop.
make the longest palindrome in a string with a single "_"
def make_longest_palindrome(s):
'''
From a string object with a single "_", return the length of the longest possible palindrome and the letter to insert in place of "_"
'''
l = list(s)
print(l)
maxlen = 0
blank = "_"
blank_temp = "_"
# check all possible ordered subsets of the list for palindrome ticker
for lefti in range(len(l)-1):
for righti in range(lefti + 1, len(l)):
pal_count = 0
if righti - lefti == 1:
if l[lefti] == l[righti] or "_" in (l[lefti], l[righti]):
pal_count += 2
if l[righti] == "_":
blank_temp = l[lefti]
elif l[lefti] == "_":
blank_temp = l[righti]
else:
if (righti - lefti + 1)%2 != 0:
pal_count += 1
if l[lefti + int((righti - lefti)/2)] == "_":
blank_temp = "any"
for step in range(int((righti - lefti + 1)/2)):
if l[lefti + step] == l[righti - step] or l[lefti + step] == "_" or l[righti - step] == "_":
pal_count += 2
if l[righti - step] == "_":
blank_temp = l[lefti + step]
elif l[lefti + step] == "_":
blank_temp = l[righti - step]
else:
break
if pal_count > maxlen:
maxlen = pal_count
blank = blank_temp
return 'The longest palindrome is ' + str(maxlen) + ' characters with "_" set to: ' + blank
if __name__ == "__main__":
valid_s = False
while not valid_s:
s = input('Word or phrase with one "_" to create longest palindrome: ')
l = list(s)
if l.count("_") < 2:
valid_s = True
print(make_longest_palindrome(s))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment