1

I am trying to make a function which takes an array and returns the array sorted by the depth:

sortArrDepth([1, [5, 6], [4, 67, [34]], 7])

Would return

[[1, 7], [5, 6, 4, 67], [34]]

However, it has to be able handle arrays with any max depth and I would prefer to not use any external modules. If it helps, here is a function to get the max depth:

def getAstDepth(ast):
    depth = 0
    for i in last:
        if isinstance(i, list):
            depth = max(getAstDepth(i), depth)
    return depth

Any help appreciated!

2 Answers 2

1

Here is one way using a recursive function:

def sortArrDepth(l, out=[], depth=0):
    if len(out)<=depth:
        out += [[] for _ in range(depth-len(out)+1)]
    for v in l:
        if isinstance(v, list):
            sortArrDepth(v, out=out, depth=depth+1)
        else:
            out[depth].append(v)
    return out

example:

>>> sortArrDepth([1, [5, 6], [4, 67, [34]], 7])
[[1, 7], [5, 6, 4, 67], [34]]

>>> sortArrDepth([1, [5, 6], [[[0]]], [4, 67, [34]], 7])
[[1, 7], [5, 6, 4, 67], [34], [0]]
Sign up to request clarification or add additional context in comments.

Comments

0

You can use itertools.zip_longest and recursion to get at the deeper levels:

from itertools import zip_longest
def sort_by_depth(seq):
    first = [item for item in seq if not isinstance(item, list)]
    nested = [sort_by_depth(item) for item in seq if isinstance(item, list)]
    return [first] + [sum(item, start=[]) for item in zip_longest(*nested, fillvalue=[])]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.