递归地扁平化带有低指针和高指针的整型嵌套列表



我看到过一些答案,它们将嵌套的整数列表(第一个代码片段)扁平化,列表作为唯一的参数:flatten(lst)。我的任务是做同样的事情,但有两个索引(低<=高),指示要考虑的索引范围:flatten(lst, low, high)

带有一个参数的工作代码

def flatten(lst):
if not lst:
return lst
if isinstance(lst[0], list):
return flatten(lst[0]) + flatten(lst[1:])
return lst[:1] + flatten(lst[1:])

我用print语句测试了我的代码,扁平化过程是正确的,问题是我不确定如何将所有的单个值放回列表中以返回它。希望这是有意义的,我不知道还有什么可以尝试。提前感谢!

我的代码

def flatten(lst, low, high):
if low > high:
return lst
elif isinstance(lst[low], list):
return flatten(lst[low], 0, len(lst[low]) - 1) + flatten(lst[low + 1:], 0, len(lst[low + 1:]) - 1)
else:
return lst[:low] + flatten(lst[low + 1:], 0, len(lst[low + 1:]) - 1)

这是我用来测试我的代码。

print(flatten([[1, 2], 3, [4, [5, 6, [7], 8]]], 0, 2))

您可以使用原始函数的下标赋值:

def flatten(lst):
if not lst:
return lst
if isinstance(lst[0], list):
return flatten(lst[0]) + flatten(lst[1:])
return lst[:1] + flatten(lst[1:])
L = [[1, 2], 3, [4, [5, 6, [7], 8]]]
L[0:2] = flatten(L[0:2])
print(L)
[1, 2, 3, [4, [5, 6, [7], 8]]]

或者实现使用第一个函数的新函数:

def flattenRange(L,low,high):
L = L.copy()
L[low:high] = flatten(L[low:high]) # use high+1 if it is inclusive
return L

或者甚至是' bastinate ',…我的意思是"增强"原文:

def flatten(lst,low=0,high=None):
if low>0 or high is not None:
lst = lst.copy()
lst[low:high] = flatten(lst[low:high]) # use high+1 if it's inclusive
return lst
if not lst:
return lst
if isinstance(lst[0], list):
return flatten(lst[0]) + flatten(lst[1:])
return lst[:1] + flatten(lst[1:])

最新更新