python-3.x - 解释器在这个程序中的工作
问题描述
这听起来像是一个愚蠢的问题,但我不得不问。以下代码检查用户输入的单词是否为回文。当我使用下面的代码时,它对所有单词都说“这个词是回文”。
word = input("Enter a word for a Palindrome : ")
word = word.replace(" ","")
k = -1
b = False
for i in range(0,len(word)):
if word[i] == word[k]:
k-=1
b=True
else:
b=False
if b:
print("The word is a Palindrome.")
else:
print("The word is not a Palindrome.")
但是当我在下一个代码块中做这个小改动时,它会正确地检测到这个词是否是回文。我在反复试验的基础上得到了这个。
word = input("Enter a word for a Palindrome : ")
word = word.replace(" ","")
k = -1
b = False
for i in range(0,len(word)):
if word[i] == word[k]:
b=True
else:
b=False
k-=1
if b:
print("The word is a Palindrome.")
else:
print("The word is not a Palindrome.")
请帮忙。提前致谢。
解决方案
目前,一些问题是您的“最终”答案基于“最后”测试。你真正想做的是,一旦你确定了,就说“不是回文”,然后停下来。
尝试:
is_a_palindrome = True
for index in range(len(word)):
if word[index] != word[- (index+1)]:
is_a_palindrome = False
break
还要注意,这在技术上可以简化为:
is_a_palindrome = word == "".join(reversed(word))
推荐阅读
- google-maps - 执行步骤后 Google Maps API 不显示地图
- javascript - 为什么使用 if 语句通过在输入上调用函数不会使值变为 false?
- r - 使用逗号分隔的字符串为每一行绘制一组值
- c++ - 如何根据两个因素组织向量:id 和数量?(C++)
- html - 粘性 div 占据所有宽度
- python - ValueError:logits 和标签必须具有相同的形状 ((None, 10) vs (None, 12))
- ssh - 来自共享 Gitlab 运行器的 SSH 停止工作
- reactjs - React useEffect 和 React-Router - 当用户导航到新页面时,在组件中重新发送 API 调用
- html - 全屏视频 iOs 设备
- get - 如何在邮递员获取请求的查询参数中发送字符串数组