1

Im trying to create a list structure in a list of strings given the depth of each string. I have no clue on how to code this. A step in the right direction would be appreciated.

strings = ["tree", "branch", "leaf", "leaf", "leaf", "branch", "tree", "tree", "branch", "tree"]
depths  = [1,2,3,3,3,2,1,1,2,1]

What im trying to get:

strings = ["tree", ["branch", ["leaf", "leaf", "leaf"], "branch"], "tree","tree", ["branch"], "tree"]

2 Answers 2

1

Here is the solution for your question. First get maximum value in the depths and decrement level by 1. If consecutive level, then append to previous array. I hope you will get it.

Whenever you try to solve these question, make a plan for how will you get to the solution and use debugger to see if your code is performing as you expected or not.

import copy

strings = ["tree", "branch", "leaf", "leaf", "leaf", "branch", "tree", "tree", "branch", "tree"]
depths  = [1,2,3,3,3,2,1,1,2,1]
output = copy.deepcopy(depths)

while max(depths)!=0:
    m = max(depths)
    last = -2
    while True:
        try:
            i = depths.index(m)
            depths[i]=m-1
            if i-1==last:
                output[i-1].append(strings[i] if isinstance(output[i], int) else output[i])
                last=i-1
                output.pop(i)
                depths.pop(i)
                strings.pop(i)
                continue
            else:
                output[i] = [strings[i]]
                last=i
        except:
            break

print(output[0])
#output[0] = ['tree', ['branch', ['leaf', 'leaf', 'leaf'], 'branch'], 'tree', 'tree', ['branch'], 'tree']
Sign up to request clarification or add additional context in comments.

Comments

0

Try to see this question. They may have some common factors. Anyway, I recommend you to search online for BFS and DFS algorithms because they are useful for your case.

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.