python - 使用 Python 的循环和 if 语句创建回文检查器
问题描述
我正在尝试按照说明创建回文。我得到了一半的功能,我必须填写空白。我目前无法让循环正常工作。我也不确定如何在不使用 + 或逗号的情况下将字符添加到字符串的开头或结尾。我不认为这是我被要求做的。这是说明;
is_palindrome 函数检查字符串是否为回文... 如果传递的字符串是回文,则填写此函数中的空白以返回 True,否则返回 False。
def is_palindrome(input_string):
# We'll create two strings, to compare them
new_string = input_string.replace(" ", "")
reverse_string = input_string.replace(" ", "")
# Traverse through each letter of the input string
for word in input_string: # Originally, I was only given the a FOR statement here, I wrote in the rest
new_string+=word.replace(" ","").upper()
# Add any non-blank letters to the
# end of one string, and to the front
# of the other string.
if ___:
new_string = ___
reverse_string = ___
# # Compare the strings
if ___:
return True
return False
print(is_palindrome("Never Odd or Even")) # Should be True
print(is_palindrome("abc")) # Should be False
print(is_palindrome("kayak")) # Should be True
我已经删除了空格并使所有内容都相同。我已将字符分配给 new_string,但看起来我应该使用 join 来添加字符,但是当我执行 print 语句时不会打印任何内容。我不确定如何以相反的顺序添加项目。我什至不确定我是否走在正确的轨道上,因为我不确定 IF 语句在问什么。我想我应该能够使用循环来创建字符串,然后比较两个字符串。
另外,有人可以解释一下为什么 new_string.join(word) 不打印任何东西吗?我如何错误地使用它?
非常感谢您提供任何可能的帮助。
解决方案
它对我有用,我已经尝试从上面的代码进行一些更改,现在它可以使用下面的代码。
您可以看到它通过了他们的测试和代码验证,请参阅下面的屏幕截图和代码。
def is_palindrome(input_string):
# We'll create two strings, to compare them
new_string = ""
reverse_string = ""
# Traverse through each letter of the input string
for letter in input_string.strip():
# Add any non-blank letters to the
# end of one string, and to the front
# of the other string.
new_string = new_string+letter.replace(" ","")
reverse_string = letter.replace(" ","")+reverse_string
# Compare the strings
if new_string.lower() == reverse_string.lower():
return True
return False
print(is_palindrome("Never Odd or Even")) # Should be True
print(is_palindrome("abc")) # Should be False
print(is_palindrome("kayak")) # Should be True
推荐阅读
- jquery - 如何从jquery中的以下json字符串中提取确切日期
- postgresql - 无法通过 NPGSQL 查询 postgresql
- python - Pandas groupby 在具有至少一个共同元素的列表列表中
- python - 未关闭但 UnitTest 正在抛出的文件的 ResourceWarning
- scala - 有没有什么优雅的方法可以返回 None 而不是基于字符串的对象
- mongodb - 如何在 MongoDB 中访问对象的动态字段
- scala - 使用scala在Spark中查看相关矩阵的所有列
- python - 有没有办法将格式从文本更改为 Excel 文件中给出的日期以用于 MailMerge 目的?
- python - 3个快速排序函数的中位数不起作用
- optaplanner - 在 Optaplanner 上需要帮助,Quarkus 与数独