如何使用 while 循环检查回文 python
How to check for palindrome using while loop python
我正在尝试使用 while 循环和索引检查回文,return 对或错。我知道这可以使用 for 循环甚至仅一行来简单得多:
return 数[::-1] == 数
(num 是函数内的参数)
click for image of code here
我很想用一个 while 循环来完成这个,如果有人能阐明我在这里做错了什么就太好了:)
顺便说一句,回文是一个单词或短语,可以以相同的方式反向阅读,例如:level、racecar、rotavator 等
def palindrome(s):
i = 0
while i <= len(s) / 2:
if s[i] != s[-i - 1]:
return False
i += 1
return True
这应该可以做到。
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.
我正在尝试使用 while 循环和索引检查回文,return 对或错。我知道这可以使用 for 循环甚至仅一行来简单得多:
return 数[::-1] == 数
(num 是函数内的参数)
click for image of code here
我很想用一个 while 循环来完成这个,如果有人能阐明我在这里做错了什么就太好了:)
顺便说一句,回文是一个单词或短语,可以以相同的方式反向阅读,例如:level、racecar、rotavator 等
def palindrome(s):
i = 0
while i <= len(s) / 2:
if s[i] != s[-i - 1]:
return False
i += 1
return True
这应该可以做到。
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.