Python中的回文

-1 python for-loop if-statement palindrome

fno = input()
myList = list(fno)
sum = 0
for i in range(len(fno)):
    if myList[0:] == myList[:0]:
    continue
print (myList)
Run Code Online (Sandbox Code Playgroud)

我想做一个回文数.例如:

input(123)
print(You are wrong)
input(12121)
print(you are right) 
Run Code Online (Sandbox Code Playgroud)

请指导我如何在python中制作回文.如果没有完整的代码请告诉我下一步是什么.

谢谢

Gar*_*tty 6

我认为,鉴于你的代码,你想检查一个回文,而不是一个.

您的代码存在许多问题,但简而言之,它可以减少到

word = input()
if word == "".join(reversed(word)):
    print("Palidrome")
Run Code Online (Sandbox Code Playgroud)

让我们谈谈你的代码,这没有多大意义:

fno = input() 
myList = list(fno) #fno will be a string, which is already a sequence, there is no need to make a list.
sum = 0 #This goes unused. What is it for?
for i in range(len(fno)): #You should never loop over a range of a length, just loop over the object itself.
    if myList[0:] == myList[:0]: #This checks if the slice from beginning to the end is equal to the slice from the beginning to the beginning (nothing) - this will only be true for an empty string.
        continue #And then it does nothing anyway. (I am presuming this was meant to be indented)
print (myList) #This will print the list of the characters from the string.
Run Code Online (Sandbox Code Playgroud)

  • `if word == word [:: - 1]` (5认同)
  • 你能证明它"可能更慢"吗?我认为我们为那些懂语法的人编写代码. (2认同)
  • @DrTyrsa有一个原因是内置的`reversed()`.Python的目标是可读性,并且`reverse(x)`比`x [:: - 1]`更清晰.至于速度较慢,类可以提供`__reversed __()`以提供更快的方法来反转它们的内容,如果有办法的话. (2认同)
  • @DrTyrsa我不是说整个Python代码页面对于非程序员来说应该是显而易见的,而是语言结构应该尽可能地对它们有意义.通过继续争论这一点,我不会再进一步​​垃圾邮件了 - 如果你真的相信`[:: - 1]`产生的反转序列比反转()更明显,那么你很清楚不同于我. (2认同)

Jes*_*ose 5

切片表示法在这里很有用:

>>> "malayalam"[::-1]
'malayalam'
>>> "hello"[::-1]
'olleh'
Run Code Online (Sandbox Code Playgroud)

有关详细介绍,请参阅解释Python的切片表示法.