【问题标题】:Why is my Python palindrome-function failing? [duplicate]为什么我的 Python 回文函数失败了? [复制]
【发布时间】:2020-09-02 16:55:58
【问题描述】:
def is_palindrome(input_string):
# We'll create two strings, to compare them
   if input_string[0:] == input_string[-1:]:
      return True
   else:
      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

我目前在所有情况下都为 False。我知道我的拼接可能在 -1 上关闭。我已经尝试交换冒号无济于事。

【问题讨论】:

  • 请从intro tour 重复how to ask。首先,研究课题。其次,跟踪您自己程序的值。其中任何一个都会立即显示您的错误。

标签: python python-3.x string while-loop palindrome


【解决方案1】:

另外,我认为您想事先删除空格并降低或提高字母。

l = ['Never Odd or Even', 'abc', 'kayak']

def isit(s):
    s = s.replace(' ', '').lower()
    return s == s[::-1]

for e in l:
    isit(e)


True
False
True

【讨论】:

    【解决方案2】:

    正如您现在所拥有的,您将所有字母与最后一个字母进行比较。

    >>> a = [1,2,3]
    >>> a[-1:]
    [3]
    >>> a[0:]
    [1,2,3]
    

    但这不是你反转字符串或任何可迭代字符串的方式。步数索引应该是负数:

    >>> a = [1,2,3]
    >>> a[::-1]
    [3,2,1]
    

    所以你只想将原始字符串与那个进行比较

    【讨论】:

    • 谢谢!我想我确实需要重新学习拼接。这帮助我通过了最后两个测试用例。我认为第一个测试用例由于空格而失败。我想我必须以某种方式使用 .join() 方法。
    猜你喜欢
    • 1970-01-01
    • 2016-12-26
    • 2015-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-13
    • 1970-01-01
    相关资源
    最近更新 更多