8-line py3 solution with explaination solution in Clear category for The Longest Palindromic by imhuwq
"""We check the sub strings of the text,
from longer to shorter, from left to right.
if any of these substring satisfies the condition of
substring == substring[::-1],
then we stop checking shorter sub strings,
and return this substring
length = len(text)
# we loop through the text, from index 0 to index length-1
for i in range(length):
# sub_count indicates the count of sub strings in this period of loop
# for example, while i==0, count of sub strings will be 1
# and while i == 1, count be 2
sub_count = i + 1
# get the sub strings
for count in range(sub_count):
# the length of the substring become shorter while we keep looping
# and that's why we substract i
sub = text[count:count + length - i]
if sub == sub[::-1]:
if __name__ == '__main__':
assert longest_palindromic("artrartrt") == "rtrartr", "The Longest"
assert longest_palindromic("abacada") == "aba", "The First"
assert longest_palindromic("aaaa") == "aaaa", "The A"
June 1, 2016