Skip to content

Instantly share code, notes, and snippets.

@msyvr
Created October 26, 2021 20:09
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/7ba0da9d52e5f156289dc617f8094dcf to your computer and use it in GitHub Desktop.
Save msyvr/7ba0da9d52e5f156289dc617f8094dcf to your computer and use it in GitHub Desktop.
find the length of the longest palindrome section in any string (word, phrase, ...)
def longest_palindrome(s):
'''
find the longest palindrome in any string object
'''
l = list(s)
print(l)
maxlen = 0
# check all possible same-ordered subsets of the list and return the length of the longest palindrome
for lefti in range(len(l)-1):
for righti in range(lefti + 1, len(l)):
pal_count = 0
if int((righti - lefti)/2) == 0:
if l[lefti] == l[righti]:
pal_count += 2
else:
if (righti - lefti + 1)%2 != 0:
pal_count += 1
for step in range(int((righti - lefti + 1)/2)):
if l[lefti + step] == l[righti - step]:
pal_count += 2
else:
break
if pal_count > maxlen:
maxlen = pal_count
return 'The longest palindrome is ' + str(maxlen) + ' characters'
if __name__ == "__main__":
s = input('Word or phrase to test for palindrome: ')
print(longest_palindrome(s))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment