在PYTHON中使用递归检查回文

时间:2017-04-27 05:19:36

标签: python recursion palindrome

我正在检查一个单词是否是一个回文,我似乎无法让我的代码作出回应。我觉得它很漂亮,但显然我错过了一些东西。有人可以指出可能是什么吗?

def reverse(usrWrd, index):   
    newWord = ""  

    if index == len(usrWrd):
        return newWord
    else:
      newWord += usrWrd[index]
      return reverse(usrWrd, index + 1)

def main(): 
    usrWrd = input("please enter a word to check for palindrome-ness:")

    result = reverse(usrWrd, 0)
    if result == usrWrd:
        print("That word is a palindrome")
    else:
        print("Sorry,",usrWrd,  "is NOT a palindrome")

main()

8 个答案:

答案 0 :(得分:0)

def isPalindrome(s):
   length = len(s);
   if length <= 1:
       return True
   if s[0] != s[length-1]:
       return False
   return isPalindrome(s[1:length-1])

对于那些喜欢更简洁代码的人:

def isPalindrome(s):
   return (len(s) <= 1) or ((s[0] == s[-1]) and isPalindrome(s[1:-1]))

答案 1 :(得分:0)

def reverse(usrWrd, index):
    newWord = ""                     # This is a local

    if index == len(usrWrd):
        return newWord               # It will always be empty string here

    else:
        newWord += usrWrd[index]
        return reverse(usrWrd, index + 1)

我不确定你为什么认为自己需要newWord。你应该比较第一个和最后一个字母是否相等,然后用你的递归函数来检查剩下的子串也是一个回文。

答案 2 :(得分:0)

如上所述局部变量是问题,可能是你可以发送局部变量。典型的尾递归实现

def reverse(usrWrd, index, newWord=''):

    if index == len(usrWrd):
        return newWord       
    else:
        newWord += usrWrd[index]
        return reverse(usrWrd, index + 1, newWord)

希望它有所帮助!

答案 3 :(得分:0)

def main():
    usrWrd = input("please enter a word to check for palindrome-ness:")

    result=reversed(usrWrd)

    if list(result) == list(usrWrd):
        print("That word is a palindrome")
    else:
        print("Word is NOT a palindrome")

答案 4 :(得分:0)

# 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

答案 5 :(得分:0)

def rec_palindrome(S, n):
    if not S:
        return False
    if n == 0:
        return True
    else:
        return S[n] == S[(len(S)-1) - n] and rec_palindrome(S, n - 1)

请提出改进​​建议

答案 6 :(得分:0)

from random import randint
import multiprocessing
import time

t = time.time()

def dice_calc(rolls):
    mutex.acquire()
    global wins
    global loss
    while rolls > 0:

        dice1 = randint(1, 6)
        dice2 = randint(1, 6)

        if dice1+dice2 == 11 or dice1+dice2 == 7 or dice1 == dice2:
            wins += 1

        else:
            loss += 1

        rolls -= 1
    mutex.release()


mutex = multiprocessing.Lock()
wins = 0
loss = 0
rolls = 1000000

if __name__ == "__main__":
    p1 = multiprocessing.Process(target=dice_calc, args=(rolls/4,))
    p2 = multiprocessing.Process(target=dice_calc, args=(rolls/4,))
    p3 = multiprocessing.Process(target=dice_calc, args=(rolls/4,))
    p4 = multiprocessing.Process(target=dice_calc, args=(rolls/4,))

    p1.start()
    p2.start()
    p3.start()
    p4.start()

    p1.join()
    p2.join()
    p3.join()
    p4.join()

    print(wins)
    print(loss)
    #percentage = (wins / (wins + loss)) * 100
    #print("Calculated percentage of a roll fulfilling requirements are:", round(percentage, 2), "%")


print(round((time.time()-t), 3))

这是您可能要检查的另一种解决方案!

答案 7 :(得分:0)

    string=string.lower()
    if(len(string)<2):
       return True 
    elif(string[0]!=string[-1]):
       return False
    else:
       return string[1:-1]
palin=is_palindrome("Abbacus")
if(palin):
  print("The string is palindrome")
else:
  print("The string is not Palindrome")