2 回答

TA貢獻1829條經驗 獲得超4個贊
我認為您的代碼中的問題在于查找子字符串。嘗試這個
def palindrome(x):
if len(x) <= 1: ## This condition checks if the length of the string is 1. And if so, it returns False
return False
return x == x[::-1]:
def longest_palindrome(s):
last = len(s)
lst = []
for i in range(last):
for j in range(i, last): ## Iterate from i to last not i+1 to last
b = s[i:j+1] ## Slicing the original string to get the substring and checking if it is a pallindrome or not.
if palindrome(b):
lst.append(b)
else:
continue
return lst
a = input("Enter the string: ")
print(longest_palindrome(a))
. 此代碼將有所幫助

TA貢獻1836條經驗 獲得超5個贊
這應該可以正常工作。
def longest_palindrome(s):
last = len(s)
lst = []
for i in range(last):
for j in range(i+1, last):
b = s[i:j+1] #Here's the catch.
a = palindrome(b)
if a:
lst.append(b)
return lst
您可以使用打印語句進行檢查。如果在代碼中添加 print 語句,您會看到最多只檢查長度為 2 的字符串(“aa”、“ab”、“ba”)。
我希望它有幫助。
添加回答
舉報