Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
Explained solution in Clear category for The Longest Palindromic by Selindian
def longest_palindromic(text):
parts = list()
textlen = len(text)
for length in reversed(range(textlen)): # Loop over the descending length (abc --> 2, 1, 0)
for start in range(textlen - length): # ... use that and another loop to calculate the starting point
parts.append(text[start: start + length + 1]) # ... ... add the found parts to the list of parts.
return next(s for s in parts if s == s[::-1]) # Return the first longest palindrom
if __name__ == '__main__':
print("Example:")
print(longest_palindromic('abc'))
# These "asserts" are used for self-checking and not for an auto-testing
assert longest_palindromic('abc') == 'a'
assert longest_palindromic('abacada') == 'aba'
assert longest_palindromic('artrartrt') == 'rtrartr'
assert longest_palindromic('aaaaa') == 'aaaaa'
print("Coding complete? Click 'Check' to earn cool rewards!")
Aug. 29, 2022
Comments: