Home > Back-end >  Recursively flatten a nested list of integers with low and high pointers
Recursively flatten a nested list of integers with low and high pointers

Time:10-24

I have seen a few answers that flattened a nested list of integers (first snippet of code) with the list as the only parameter: flatten(lst). My assignment is to do the same but with two indices (low <= high) that indicates the range of indices to be considered: flatten(lst, low, high).

Working code with one parameter

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:])

I tested my code with print statements and the flattening process is correct, the problem is I'm not sure how to put all the individual values back into the list to return it. Hopefully this makes sense, I'm not sure what else to try. Thank you in advance!

My code

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)

This is what I'm using to test my code.

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

CodePudding user response:

You could have used the original function as-is with subscript assignment:

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]]]

Or implement a new function that uses the first one:

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

Or even 'bastardize', ... I mean 'enhance' the original:

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:])
  • Related