如何解决在python中不使用[::-1]检查字符串是否为回文
def checker(string):
collection=list(string)
print(collection)
while string.isalpha()==True:
copy_collection=collection
copy_collection.reverse()
print(copy_collection)
if copy_collection==collection:
print("The string is a palindrome")
else:
print("The string is not a palindrome")
break
name=input("Enter a string: ")
checker(name)
我想知道用户输入的字符串是否是回文。 大多数解决方案建议使用 [::-1]。是否可以不使用它,因为我们的讲师没有教过我们,并告诉我们不要在课程之外编写程序。
if copy_collection==collection:我认为问题出在这里,因为即使它不是,它也会打印出“字符串是回文”。
提前致谢。
解决方法
您可以将列表 copy_collection
转换为字符串,然后将其与原始 string
进行比较。
看看:
def checker(string):
collection=list(string)
print(collection)
while string.isalpha()==True:
copy_collection=collection
copy_collection.reverse()
print(copy_collection)
#Here the conversion to string
copy_collection = ''.join(copy_collection)
print(copy_collection)
#compare to the vatiable "string"
if copy_collection==string:
print("The string is a palindrome")
else:
print("The string is not a palindrome")
break
name=input("Enter a string: ")
checker(name)
输出:
Enter a string: somestring
['s','o','m','e','s','t','r','i','n','g']
['g','s']
gnirtsemos
The string is not a palindrome
现在是回文:
Enter a string: somemos
['s','s']
['s','s']
somemos
The string is a palindrome
,
def checker(string):
collection=list(string)
length = len(collection)
isPalindrom = True
for i in range(length):
if collection[i] != collection[length-i-1]:
isPalindrom = False
break;
if isPalindrom :
print('String is Palindrome')
else:
print('String is not Palindrome')
name=input("Enter a string: ")
checker(name)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。