我需要帮助编写一个递归函数,用于检测一个字符串是否为回文。但是我不能使用任何循环而必须使用递归。有人能帮助我展示如何实现吗?我正在使用Python。
我需要帮助编写一个递归函数,用于检测一个字符串是否为回文。但是我不能使用任何循环而必须使用递归。有人能帮助我展示如何实现吗?我正在使用Python。
def ispalindrome(word):
if len(word) < 2: return True
if word[0] != word[-1]: return False
return ispalindrome(word[1:-1])
这里是最佳单行代码
def ispalindrome(word):
return word == word[::-1]
既然我们已经在发布代码,而且还没有发布一行代码,那就来吧:
def palindrome(s):
return len(s) < 2 or s[0] == s[-1] and palindrome(s[1:-1])
如果一个字符串长度为零或一,那么它是回文的。
如果一个字符串的第一个和最后一个字母相同,并且剩余的字母(我认为在Python中是[1: -1]
切片,但我的Python有点生疏)也是回文的,则它是回文的。
现在,编写一个接受字符串参数的回文函数。它将会调用自己。
以下是一种思考简单递归函数的方法...将问题颠倒过来,以这种方式思考。如何递归地创建回文?这是我会这样做的...
def make_palindrome():
maybe:
return ""
elsemaybe:
return some_char()
else:
c = some_char()
return c + make_palindrome() + c
palindrom( word):
IF length of word 1 or 0 THEN
return 0;
IF last and first letter equal THEN
word := remove first and last letter of word;
palindrom( word);
ELSE
return false;
a=raw_input("enter the string:")
b=len(a)
c=0
for i in range(b):
if a[i]==a[-(i+1)]:
c=c+1
if c==b:
print a,"is polindrome"
else:
print a,"is not polindrome"
我的解决方案
#To solve this I'm using the stride notation within a slice [::]
def amazonPalindrome(input):
inputB = input
input = input[::-1]
#print input
noPalindrome = inputB + " is not a palindrome"
isPalindrome = inputB + " is a palindrome"
#compare the value of the reversed string to input string
if input[0]!= input[-1]:
print noPalindrome
else:
print isPalindrome
#invoking the def requires at least 1 value or else it fails
#tests include splitting the string,mixing integers, odd amount palindromes.
#call the def
amazonPalindrome('yayay')
n=raw_input("Enter a number===>")
n=str(n)
l=len(n)
s=""
for i in range(1,l+1):
s=s+n[l-i]
if s==n:
print "Given number is polindrom"
else:
print "Given number is not polindrom"