我正在尝试编写一个具有三个输入的递归函数,即列表、列表第一个字符的索引位置和列表最后一个字符的索引位置,它返回 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/