# Correct approach to your solution
def reverse(usrWrd, index, newWord):
if index < 0:
return newWord
else:
newWord += usrWrd[index]
return reverse(usrWrd, index - 1, newWord)
def main():
newWord = ""
usrWrd = input("please enter a word to check for palindrome-ness:")
result = reverse(usrWrd, len(usrWrd) - 1, newWord)
if result == usrWrd:
print("That word is a palindrome")
else:
print("Sorry,",usrWrd, "is NOT a palindrome")
######################################### ####################
# Alternate approach
def isPalindrome(usrWord):
sLen = len(usrWord)
if sLen <= 1:
return True
else:
if usrWord[0] != usrWord[sLen-1]:
return False
else:
return isPalindrome(usrWord[1:sLen-1])
def main():
newWord = ""
usrWrd = input("please enter a word to check for palindrome-ness:")
result = isPalindrome(usrWrd)
if result:
print("That word is a palindrome")
else:
print("Sorry,",usrWrd, "is NOT a palindrome")
######################### ####################################
# Pythonic way as suggested by 'Yaman Jain'
if usrWord == usrWord[::-1]:
return True # Palindrome
else:
return False # Not Palindrome
要設置'newWord'到空字符串每次在'reverse()' – kuro
也用'len(usrWrd) - 1'而不是'0'調用'reverse' – kuro
pythonic方式 's == s [:: - 1]'如果s是palidrome海峽否則爲假 –