Python 3.x 回文的反向循环
我的老师希望我使用反向循环,而不是我现在使用的反向函数。我似乎找不到一个有效的Python 3.x 回文的反向循环,python-3.x,loops,reverse,Python 3.x,Loops,Reverse,我的老师希望我使用反向循环,而不是我现在使用的反向函数。我似乎找不到一个有效的 def palindrome(): myInput = input("Enter a Word: ") word = myInput[::-1] if myInput == word: print("That is a palindrome") return True else: print("That is not a palindro
def palindrome():
myInput = input("Enter a Word: ")
word = myInput[::-1]
if myInput == word:
print("That is a palindrome")
return True
else:
print("That is not a palindrome")
return False
palindrome()
您可以尝试下面的代码,但我真的建议您先自己尝试。(因为,如果您能够编写递归调用,您也应该能够自己编写迭代调用。) 编辑以下评论: 函数的作用是:向iterable中添加一个计数器 所以行
if char!=字符串[-i-1]
将尝试从前面匹配一个字符,从后面匹配一个字符
这对我来说很好。是的,我知道它是有效的,只是我的老师想让我使用一个循环,而不是反向函数。它的反向循环实现。list(reversed(myInput))==list(myInput)会使用保留函数。您能解释一下它是如何工作的以及为什么工作的吗?我对语言还很陌生。如果我的答案解决了你的问题,请将其标记为已接受,因为它可能也会帮助其他用户。
def reverse(text):
rev = ""
final = ""
for a in range(0,len(text)):
rev = text[len(text)-a-1]
final = final + rev
return final
def palindrome():
string = input("Enter a Word: ")
for i,char in enumerate(string):
if char != string[-i-1]:
return False
return True
>>> string = "PARAM"
>>> for count, elem in enumerate(string):
... print count, elem
...
0 P
1 A
2 R
3 A
4 M