如何使用while循环python检查回文

问题描述 投票:0回答:2

我正在尝试使用while循环和索引来检查回文,返回True或False。我知道使用for循环甚至只需一行就可以做得更简单:return num [:: - 1] == num (num是函数内部的参数)click for image of code here

我想用一个循环完成这个,如果有人能说明我做错了什么会很好:)

顺便说一下,回文是一个单词或短语,可以通过相反的方式读取,例如:水平,赛车,旋转器等

python indexing while-loop palindrome
2个回答
1
投票
def palindrome(s):
    i = 0
    while i <= len(s) / 2:
        if s[i] != s[-i - 1]:
            return False
        i += 1
    return True

这应该做到这一点。


0
投票
str = input("Enter a string: ") #taking a string from user & storing into variable.
li = list(str) #converting the string into list & storing into variable.
ln = len(li) #storing the length of the list into a variable.
revStr = "" #defining an empty variable (which will be updated & will be final result to check palindrome).
i = ln - 1 #value of i will be used in loop.

while i >= 0: #here logic is to start from right to left from the list named "li". That means going from last to first index of the list till the index value is "0" of the "li" list.
    revStr = revStr + li[i] #concatenating & updating the "revStr" defined variable.
    i = i - 1 #decreasing the value of i to reach from the last index to first index.
str = str.lower() #converting value into lowercase string.
revStr = revStr.lower() #converting the final output into lowercase string to avoid case sensitive issue.

if str == revStr: #the two string is same or not?
    print(str, ", is PALINDROME!") #if same.
else:
    print(str, ", isn't PALINDROME!") #if not same.
© www.soinside.com 2019 - 2024. All rights reserved.