【发布时间】:2010-10-31 10:16:09
【问题描述】:
我需要帮助编写一个检测字符串是否为回文的递归函数。但我不能使用任何循环,它必须是递归的。谁能帮我看看这是怎么做到的。我正在使用 Python。
【问题讨论】:
标签: python recursion palindrome
我需要帮助编写一个检测字符串是否为回文的递归函数。但我不能使用任何循环,它必须是递归的。谁能帮我看看这是怎么做到的。我正在使用 Python。
【问题讨论】:
标签: python recursion palindrome
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]
【讨论】:
从一般算法的角度来看,递归函数有3种情况:
1) 还剩 0 项。项目是palindrome,按身份标识。
2) 还剩 1 项。项目是palindrome,按身份标识。
3) 2 个或更多项目。删除第一个和最后一个项目。比较。如果它们相同,则在字符串的左侧调用函数。如果 first 和 last 不相同,则 item 不是 palindrome。
函数本身的实现留给读者作为练习:)
【讨论】:
如果一个字符串的长度为零或一个字母,则它是回文。
如果一个字符串的首尾字母相同,而其余字母(我认为它是 Python 中的 [1: -1] 切片,但我的 Python 有点生疏)是回文,那就是回文。
现在,把它写成一个接受字符串的回文函数。它会调用自己。
【讨论】:
由于我们无论如何都在发布代码,并且还没有发布任何单行代码,所以这里是:
def palindrome(s):
return len(s) < 2 or s[0] == s[-1] and palindrome(s[1:-1])
【讨论】:
这是另一种观点
回文串是
一些字母,x。
一些回文子串。
同一个字母,x,重复了。
另外,请注意,您可能会得到一个正确的英文句子“Able was I ere I saw Elba”。用标点符号。您的回文检查器可能不得不悄悄地跳过标点符号。此外,您可能不得不在不考虑大小写的情况下悄悄匹配。这稍微复杂一些。
一些前导标点符号。一些字母,x。
一些回文子串。
某个字母,x,不分大小写重复。一些尾随标点符号。
而且,根据定义,长度为零的字符串是回文。单字母字符串(去除标点符号后)也是回文。
【讨论】:
您可以通过以下方式来考虑简单的递归函数...绕过问题并以这种方式思考。你如何递归地制作回文?这就是我的做法......
def make_palindrome():
maybe:
return ""
elsemaybe:
return some_char()
else:
c = some_char()
return c + make_palindrome() + c
然后你可以翻转它来构建测试。
【讨论】:
函数应该期望一个字符串。如果字符串中有多个字母,则比较第一个和最后一个字母。如果是 1 或 0 个字母,则返回 true。如果两个字母相等,则再次使用字符串调用函数,不带第一个和最后一个字母。如果它们不相等,则返回 false。
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;
【讨论】:
我的解决方案
#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')
【讨论】:
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"
【讨论】:
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"
【讨论】:
这里是C版本,如果有人碰巧登陆这里搜索C代码!
int IsPalindrome_Recursive(char *s, int start, int end)
{
if ((end - start) < 2)
{
return 1;
}
if (s[start] != s[end])
{
return 0;
}
return IsPalindrome_Recursive(s, ++start, --end);
}
调用为:
IsPalindrome_Recursive(s, 0, strlen(s) - 1)
【讨论】: