简体   繁体   English

如何使用递归通过Python查找回文?

[英]How can I use recursion to find palindromes using Python?

I've just started exploring the wonders of programming. 我刚刚开始探索编程的奇迹。 I'm trying to write a code to identify numeric palindromes. 我正在尝试编写代码以识别数字回文。 Just looking at numbers and not texts. 只看数字而不是文字。 I'm trying to learn to use recursion here. 我正在尝试学习在这里使用递归。 But I'm just not getting anywhere and I can't figure out what's wrong with it. 但是我什么都没走,我也弄不清这是怎么回事。

My idea was to check first string vs the last, then delete these two if they match, and repeat. 我的想法是检查第一个字符串与最后一个字符串,如果匹配则删除这两个字符串,然后重复。 Eventually there'll be nothing left (implying it is a palindrome) or there will be a couple that doesn't match (implying the reverse). 最终将一无所有(暗示这是回文),或者会有一对不匹配的事物(暗示相反)。

I know there are better codes to finding palindromes in but I just wanted to try my hand at recursion. 我知道有更好的代码可以找到回文,但是我只是想尝试递归。

So what's wrong? 那怎么了

def f(n):
    global li   
    li=list(str(n))
    if (len(li)==(1 or 0)):
        return True
    elif li[len(li)-1]==li[0]:
        del li[0]
        del li[len(li)-1]
        if len(li)==0:
            return True
        if len(li)>0:
            global x
            x=''.join(li)
            str(x)
            f(x)
    else:
      return False

Thanks in advance! 提前致谢!

A few comments 一些评论

  • Why are x and li globals? 为什么xli全局变量? In recursion, all variables should be local. 在递归中,所有变量都应为局部变量。
  • Why are you converting back and forth between str and list ? 为什么要在strlist之间来回转换? You can subscript both of them 您可以将它们都下标
  • You need to return the result of your recursive call: return f(x) 您需要返回递归调用的结果: return f(x)

Try these suggestions, and see how it works out. 尝试这些建议,看看如何解决。

Before looking into it too much, if (len(li)==(1 or 0)): doesn't do what you're expecting it to do. 在过多研究它之前, if (len(li)==(1 or 0)):未执行您期望的操作。 (1 or 0) will always evaluate to 1 . (1 or 0)将始终为1

You probably want: 您可能想要:

if len(li) in (1, 0):

There are a couple of problems with your solution. 您的解决方案有两个问题。 Let me analyse them line by line. 让我逐行分析它们。

  1. You don't need global statements if you don't intend to change variables outside of function scope. 如果您不打算在函数范围之外更改变量,则不需要global语句。 Thus, I removed two lines with global from your code. 因此,我从代码中删除了两行带有global行。

  2. li=list(str(n)) : casting a string to a list is unnecessary, as a string in Python has a similar interface to an immutable list. li=list(str(n)) :不需要将字符串强制转换为列表,因为Python中的字符串具有与不可变列表相似的接口。 So a simple li = str(n) will suffice. 因此,简单的li = str(n)就足够了。

  3. if (len(li)==(1 or 0)): : although it looks OK, it is in fact an incorrect way to compare a value to a few other values. if (len(li)==(1 or 0)):尽管看起来不错,但实际上是将一个值与其他几个值进行比较的不正确方法。 The or operator returns the first "true" value from its left or right operand, so in this case it always returns 1 . or运算符从其左侧或右侧操作数返回第一个“ true”值,因此在这种情况下,它始终返回1 Instead, you can use the in operator, which checks whether the left operand is an element of a right operand. 而是可以使用in运算符,该运算符检查左操作数是否是右操作数的元素。 If we make the right operand a tuple (1, 0) , all will be well. 如果我们将正确的操作数设为元组(1, 0) ,那么一切都会很好。 Furthermore, you don't need parentheses around the if statement. 此外,您不需要在if语句周围加上括号。 You should write: if len(li) in (1, 0): 您应该输入: if len(li) in (1, 0):

  4. elif li[len(li)-1]==li[0]: is fine, but we can write this shorter in Python, because it supports negative list indexing: elif li[-1] == li[0]: elif li[len(li)-1]==li[0]:很好,但是我们可以在Python中写得短一些,因为它支持负列表索引: elif li[-1] == li[0]:

  5. Because we don't use lists (mutable sequences) because of point 2., we can't do del li[0] on them. 因为由于第2点,我们不使用列表(可变序列),所以我们无法对它们执行del li[0] And anyway, removing the first element of a list is very inefficient in Python (the whole list must be copied). 而且无论如何,删除列表的第一个元素在Python中效率非常低(必须复制整个列表)。 From the very same reason, we can't do del li[len(li)-1] . 由于同样的原因,我们不能进行del li[len(li)-1] Instead, we can use the "splicing" operator to extract a substring from the string: li = li[1:-1] 相反,我们可以使用“ splicing”运算符从字符串中提取子字符串: li = li[1:-1]

  6. if len(li)==0: is unnecessary long. if len(li)==0:不需要很长。 In Python, empty strings and lists resolve to False if tested by an if . 在Python中,如果通过测试空字符串,并列出解决为False if So you can write if not li: 所以你可以写, if not li:

  7. if len(li)>0: : You don't have to check again if li is not empty -- you checked it in point 6. So a simple else: would suffice. if len(li)>0:如果li不为空,则无需再次检查-您在第6点中进行了检查。因此,一个简单的else:就足够了。 Or even better, remove this line completely and unindent the rest of the function, because the body of the if in 6. contains a return . 甚至更好的是,完全删除此行,并使函数的其余部分不缩进,因为6.中if的主体包含return So if we didn't enter the if , we are in the else without writing it at all. 因此,如果我们不输入if ,那么我们将进入else而不编写它。

  8. x=''.join(li) : We don't need to convert our string to a string, because of the decision made in 2. Remove this line. x=''.join(li) :由于2中的决定,我们不需要将字符串转换为字符串。删除此行。

  9. str(x) : This line didn't do anything useful in your code, because str() doesn't modify its argument in place, but returns a new value (so x = str(x) would have more sense). str(x) :该行在您的代码中没有做任何有用的事情,因为str()不会适当修改其参数,而是返回一个新值(因此x = str(x)更具意义)。 You can also remove it. 您也可以删除它。

  10. f(x) : This is a valid way to call a recursive function in Python, but you have to do something with its value. f(x) :这是在Python中调用递归函数的有效方法,但是您必须对其值进行某些处理。 Return it perhaps? 还可以退还吗? We'll change it to: return f(li) (as we don't have an x variable any more). 我们将其更改为: return f(li) (因为我们不再有x变量了)。

We end up with the following code: 我们最终得到以下代码:

def f(n):
    li = str(n)
    if len(li) in (1, 0):
        return True
    elif li[-1] == li[0]:
        li = li[1:-1]
        if not li:
            return True
        return f(li)
    else:
        return False

It's almost what we need, but still a little refinement can be made. 这几乎是我们所需要的,但是仍然可以进行一些改进。 If you look at the lines if not li: return True , you'll see that they are not necessary. 如果您查看if not li: return True的行if not li: return True ,您会发现它们不是必需的。 If we remove them, then f will be called with an empty string as the argument, len(li) will equal 0 and True will be returned anyway. 如果删除它们,则将使用空字符串作为参数调用flen(li)等于0,并且无论如何将返回True So we'll go ahead and remove these lines: 因此,我们将继续删除以下几行:

def f(n):
    li = str(n)
    if len(li) in (1, 0):
        return True
    elif li[-1] == li[0]:
        li = li[1:-1]
        return f(li)
    else:
        return False

And that's it! 就是这样! Good luck on your way to becoming a successful programmer! 祝您成功成为一名程序员,祝您好运!

Split the whole show out into a list, then just: 将整个节目分成一个列表,然后:

def fun(yourList):
    if yourList.pop(0) == yourList.pop(-1):
        if len(yourList) < 2:
            return True # We're a palindrome
        else:
            return fun(yourList)
    else:
        return False # We're not a palindrome

print "1234321"
print fun(list("1234321")) # True
print "6234321"
print fun(list("6234321")) # False
def palindrome(n):
    return n == n[::-1]
number = int(raw_input("Enter a number: "))

rev = 0
neg = number

original = number


if (number < 0):
    number = number * -1

else:

    number = number

while ( number > 0 ):

     k = number % 10

     number = number / 10

     rev = k + ( rev * 10 )

     if (number < 1):
         break

if ( neg < 0 ):
    rev =  ( rev * -1)

else:

    rev = (rev)

if ( rev == original):

    print "The number you entered is a palindrome number"

else:

    print "The number you entered is not a palindrome number"

This code even works for the negative numbers i am new to programming in case of any errors dont mind. 该代码甚至适用于负数,如果您介意任何错误,我是编程新手。

It's hard to tell what you intend to do from your code, but I wrote a simpler (also recursive) example that might make it easier for you to understand: 从代码中很难说出您打算做什么,但是我写了一个更简单(也是递归)的示例,它可能使您更容易理解:

def is_palindrome(num):
    s = str(num)
    if s[0] != s[-1]:
       return False
    elif not s[1:-1]:
       return True
    else:
       return is_palindrome(int(s[1:-1]))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM