Created
October 26, 2021 20:09
-
-
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, ...)
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
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