Slicing solution in Clear category for The Longest Palindromic by Nikolay__Pasko
# first we check the maximum length (length of the entire text
length = len(text)
# length will gradually get smaller, until a single char is checked (which is palinfrome
# by itself)
while length > 0:
# based on current substring length, there could be only so many substrings
for i in range(0, len(text)-length+1):
# get substring of current length, by straight slicing
straight = str(text[i:i+length])
# get substring of current length, by reverse slising
# take into account a borderline situation: Python fails to slice, for example,
# text[5:-1:-1], as the second index is out of bounds. In that case, slice it
# "to the limit" by not specifying the second index at all
reverse = str(text[i+length-1:i-1:-1]) if i-1>=0 else str(text[i+length-1::-1])
if straight == reverse:
length -= 1
if __name__ == '__main__':
assert longest_palindromic("abcd") == "a", "The single"
assert longest_palindromic("aaaa") == "aaaa", "The A"
assert longest_palindromic("artrartrt") == "rtrartr", "The Longest"
assert longest_palindromic("abacada") == "aba", "The First"
March 3, 2017