【问题标题】:polindrom in python function for list列表的python函数中的回文
【发布时间】:2021-02-25 21:02:53
【问题描述】:

我需要编写一个函数,如果列表是 polindrom,则返回 true,如果不是,则返回 false:

is_palindrome([]): True
is_palindrome([‘s’]): True
is_palindrome([1,4,'g','g',4,1]): True
is_palindrome(['a','c','v']): False
is_polindrom[1,"g","1]: false

这是我的代码:

import copy
        def is_polindrom(lst):
          if len(lst)<=1:
           return True
          copy_lst = copy.copy(lst)
          reverse_copy = copy_lst.reverse()
          for i,j in reverse_copy,copy_lst:
             if reverse_copy[i].type()==copy_lst[j].type() and reverse_copy[i]==copy_lst[j]:
                return True
             else:
               return False

       is_polindrom([1,2])

当我使用 ["s"] 而不是 true 时不会返回任何内容 对于:

is_polindrom([1,2]):
for i,j in reverse_copy,copy_lst:
TypeError: cannot unpack non-iterable NoneType object

我不允许使用负数或部分索引,例如:

my_list[start:]
my_list[:end]
my_list[::step]
my_list[-idx]
my_list[:,idx]

谢谢你:)

【问题讨论】:

    标签: list function return


    【解决方案1】:

    您的代码有 5 个错误:

    1. 当你遍历 reverse_copy 和 copy_lst 时,你正在做
    reverse_copy[i], copy_lst[j]
    

    当你应该做的时候

    i, j
    

    因为在这种情况下,您只是遍历每个项目,而不是通过每个项目的 INDEX。

    1. reverse() 没有返回值,因此您不能将列表设置为反向列表。您必须先创建列表,然后调用
    example_lst.reverse()
    

    反转它。

    1. 您不能像调用方法一样调用 type() - 它是一个函数,而不是一个方法。所以不是
    i.type()
    

    你必须这样做

    type(i)
    
    1. 要一次遍历 2 个列表,您必须使用 zip() 函数,否则它不起作用。
    for i, j in zip(lst1, lst2):
    
    1. 您不能在比较一对后立即返回 True,否则在遍历列表时,您只会在比较第一个项目后返回 True。相反,您可以将结果添加到 answer_list 然后返回
    all(answer_list)
    

    如果answer_list 的项目都为真,则返回真。 (is_polindrom 为 [1, 2] 返回 False 的原因是因为您没有使用 zip() 函数,因此您实际上并没有遍历项目。)

    以下是完整的更正代码(注意我使用 Python 的内置列表函数来创建 lst 的副本):

    def is_polindrom(lst):
        if len(lst)<=1:
            return True
        copy_lst = list(lst)
        reverse_copy = list(lst)
        reverse_copy.reverse()
        answer_list = []
        for i,j in zip(reverse_copy,copy_lst):
            if type(i)==type(j) and i==j:
                answer_list.append(True)
            else:
                answer_list.append(False)
        return all(answer_list)
            
    lst = [1, 2]
    # Prints is_polindrom([1, 2]): False
    print("is_polindrom([1, 2]): " + str(is_polindrom(lst))) 
    print(lst) # Prints [1, 2]
    

    【讨论】:

    • 我可以使用 print(is_polindrom(lst)) 返回 true false 吗? ' 在我的家庭作业中应该是这样的 :is_palindrome([]): True without print before the function
    • @ZivAqua 要回答您的问题,您不需要打印出来;我这样做的唯一原因是查看函数的结果。
    • 问题是我不能在调用函数之前使用 print:print(is_polindrom(lst)),需要在不调用 print 的情况下看到结果
    • @ZivAqua 好的,我明白你现在在说什么。让我编辑我的答案。
    • @ZivAqua 如果这个答案对你有帮助,请接受它以帮助其他人找到它。
    猜你喜欢
    • 2017-06-21
    • 1970-01-01
    • 2017-07-22
    • 2013-02-19
    • 2011-11-18
    • 1970-01-01
    • 2013-10-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多