python - 我需要使用递归函数来检查列表是否被镜像(相同的正向和反向)

标签 python python-3.x list recursion

我正在尝试编写一个具有三个输入的递归函数,即列表、列表第一个字符的索引位置和列表最后一个字符的索引位置,它返回 True 如果列表是镜像的,False 如果不是。对于以下代码

def is_mirror(list_to_check, first_position, last_position):
    if len(list_to_check) <= 1 :
        return True
    if list_to_check[first_position] == list_to_check[last_position]:
        return is_mirror(list_to_check, first_position + 1, last_position - 1)
    else :
        return False

当我尝试运行以下命令时:

a = [1, 2, 2, 1]
print(is_mirror(a, 0, len(a) - 1))

我得到一个错误提示

list index out of range

这应该在运行时打印 True

谁能告诉我我做错了什么?

编辑

它必须是递归函数,因为任务要求我使用递归函数。

最佳答案

你可以这样做:

l == l[::-1]

这将为

返回 False
l = [1, 2, 3]

为真

对于

l = [1, 2, 1]

关于python - 我需要使用递归函数来检查列表是否被镜像(相同的正向和反向),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41992227/

相关文章:

python - 如何在 Python 列表中找到第 1、2、3 个最高值

python - 使用其 Id 获取 TreeView 项的文本 - Treeview Tkinter

python - 在 Python 中动态覆盖 __functions__

python - Python 单元测试套件

html - Django项目中大量页面如何组织分页?

python - 在 python 中使用 pid 列表杀死所有进程?

python - 加速pandas groupby中的滚动总和计算

python - sqlite3.操作错误: no such table: django_content_type

python - 两个类之间共享资源

java - 表示列表数组