当前位置: 首页 > 知识库问答 >
问题:

用Python的循环和if语句创建回文检查器

强志学
2023-03-14

我正试图按照指示创建回文。给我半个函数,我得填空。我目前无法使循环正常工作。我也不确定如何在不使用+或逗号的情况下将字符添加到字符串的开头或结尾。我不认为这是我被要求做的。这是说明书;

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

共有1个答案

颛孙铭
2023-03-14

它为我工作,我已经尝试和改变一点点从上面我的代码,它现在与下面的代码工作。

你可以看到它通过了测试和代码验证,参考下面的截图和代码。

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
 类似资料:
  • if语句 (实际上是if表达式) OCaml有两种if语句: if boolean-condition then expression if boolean-condition then expression else other-expression 不同于传统的语言,if语句是表达式。它们更类似于C类语言中的三元操作符?: 而不是你所熟悉的if语句。 下面是if语句的简单例子: # le

  • 问题内容: 我知道如何在单独的行上同时使用for循环和if语句,例如: 而且我知道当语句很简单时,我可以使用列表推导来组合这些内容,例如: 但是我找不到一个很好的例子,可以在任何地方(复制和学习)演示一组复杂的命令(不仅仅是“ print x”),这些命令是在for循环和某些if语句组合后发生的。我期望的是: 这不是python应该工作的方式吗? 问题答案: 您可以使用以下生成器表达式:

  • 所以程序应该是:-获取用户的输入,直到用户键入“n或N”以显示停止的标志-当用户键入“n或N”时,程序正数和负数和。 还有我得到的 这个错误信息,我不知道是什么问题。提前谢谢你!

  • 这个程序基本上允许用户输入任何单词,直到他/她输入单词“last”。 如果单词包含字母“s”,则应显示单词确实包含“s”或“s”,否则应显示单词不包含“s”或“s”。 示例:用户输入的单词= •约翰 詹姆斯 •馅饼 莎莉 结果: 约翰不包含's'或'S' James确实包含“s”或“s” 馅饼不含's'或'S' Sally不包含“s”或“s” 该程序可以工作,但我需要更改if语句,以便它使用equ

  • 我试图使用while循环和索引检查回文,返回True或False。我知道,使用for循环,甚至只需一行就可以简单得多:return num[:-1]==num (num是函数中的参数)单击此处查看代码图像 如果有人能告诉我我做错了什么,我很乐意用一段时间来完成这个循环:) 顺便说一下,回文是一个单词或短语,可以用相反的方式阅读,例如:水平,赛车,旋转器等

  • 有可能做如下事情吗: 或者: 我知道用很多if-else语句也可以实现同样的目标,但如果它像上面那样工作,看起来会更干净。