【问题标题】:Trying to achieve this output of palindrome (python language). I have tried this试图实现回文(python语言)的这种输出。我试过这个
【发布时间】:2020-05-04 22:45:00
【问题描述】:

我正在尝试让我的代码打印此输出。

这是我的代码

outputlist = []
bad_character=['! ', ',']

def is_palindrome(alist):

for element in alist:
for s in word:
    if s is bad_character:
        continue
        my_stack.append(s.lower))

        my_stack_reverse=my_stack[::-1]

        if my_stack_reverse==my_stack

        outputlist.append(True)

        else
        append(False)

            if my_stack_reverse=my_stack
   test_list=['Madam', 'A nut for a jar of Tuna', 'I love DSAG']
   print(is_palindrome(test_list))
   print(test_list)

我正在尝试将此作为我的输出,但输出错误:

[对,对,错]

['女士','一罐金枪鱼的坚果','我爱 DSAG']

【问题讨论】:

标签: python jupyter-notebook stack


【解决方案1】:

下面的代码完成了你想要的。确保空格 (' ') 包含在 bad_character 列表中。我使用 replace() 方法使坏字符的删除更加干净,您可以一次对整个字符串使用 lower() 方法,而不是逐个字符地进行。此外,您可以通过附加比较 element == element[::-1] 来跳过函数末尾的 if/else,因为这将产生您想要的布尔值。

def ispalindrome(alist):
    outputlist = []
    bad_character = [' ']
    for element in alist:
        for character in bad_character:
            element = element.replace(character, '')
        element = element.lower()
        outputlist.append(element == element[::-1])
    return outputlist

test_list = ['Madam', 'A nut for a jar of Tuna', 'I love DSAG']
print(ispalindrome(test_list))
print(test_list)

【讨论】:

    猜你喜欢
    • 2020-05-05
    • 2020-03-05
    • 2010-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多