我想寫一個Python函數,它返回true一個字符串s是一個迴文,即它等於它的反向。例如'racecar'和'abba'是迴文。到目前爲止,這是我不成功的嘗試。遞歸函數無法返回布爾型
def ispalindrome(s):
if len(s) == 1:
return s
else:
reverse = s[-1] + ispalindrome(s[:-1])
我沒有問題,當我告訴我的函數返回相反,但是,我很困惑,我應該怎麼做才能返回一個布爾比較。
def ispalindrome(s):
if len(s) == 1:
return s
else:
reverse = s[-1] + ispalindrome(s[:-1])
return a == reverse
使用上述函數創建以下錯誤
>>>ispalindrome('racecar')
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
ispalindrome('racecar')
File "/Users/Nadir/Desktop/Untitled.py", line 24, in ispalindrome
reverse = s[-1] + ispalindrome(s[:-1])
File "/Users/Nadir/Desktop/Untitled.py", line 24, in ispalindrome
reverse = s[-1] + ispalindrome(s[:-1])
File "/Users/Nadir/Desktop/Untitled.py", line 24, in ispalindrome
reverse = s[-1] + ispalindrome(s[:-1])
File "/Users/Nadir/Desktop/Untitled.py", line 24, in ispalindrome
reverse = s[-1] + ispalindrome(s[:-1])
File "/Users/Nadir/Desktop/Untitled.py", line 24, in ispalindrome
reverse = s[-1] + ispalindrome(s[:-1])
TypeError: Can't convert 'bool' object to str implicitly
現在我完全理解爲什麼上述錯誤產生。這是因爲一些遞歸函數返回一個布爾值並嘗試將其添加到一個字符串;但我不能做的是如何避免這個錯誤。
爲什麼不直接測試第一個和最後一個字符,並在遞歸之前將它們關閉? – 2015-02-12 03:29:32
我可以,但我正在尋找一種方法,我可以使用生成的「反向」。 – TheValars 2015-02-12 03:32:25