如何在Python中创建最简单的回文功能? [关闭]

问题描述 投票:-4回答:2

定义一个在Python中识别回文(即看起来与反义的单词相同)的palindrome()函数。即:is_palindrome(“雷达”)应返回True。

I did this.

 def inverse (chain):
 inv = ""
 cont = len(chain)
 index = -1
 while cont >= 1:    
    inv += chain[index]
    index = index + (-1)
    cont -= 1    
 return inv

     def is_palindromo (chain):
        word_inv = inverse (chain)
        index = 0
        cont = 0
        for i in range (len(chain)):
            if word_inv[index] == chain[index]:
                index += 1
                cont += 1
            else:
                print "Its not palyndrome"
                break

        if cont != len(chain): 
            print "It is"



      But its not working. Thanks in advance.
python function inverse
2个回答
-1
投票

您可以使用内置的reversed函数检查回文:

reversed
def is_palindrome(input):
  # This creates a reverse iterator and then 'joins' them together into a single string
  reverse = ''.join(reversed(input))
  # Make sure the upper/lowercase can be handeled
  return reverse.lower() == input.lower()

-1
投票

所以,您想知道为什么它不起作用?还是您需要建议?

两种方法都可以使所有代码短很多。

>>> is_palindrome("radar")
True
def is_palindrome(word):
    return word == word[::-1]

print(is_palindrome('radar'))

它测试输入是否等于自己的反向。

© www.soinside.com 2019 - 2024. All rights reserved.