1

Hello I am learning how to construct recursive functions in python.

I have been struggling for along time now on how to print out a tree that is represented lists.

The tree is represented as lists. The first element of a list is the data or value of the node, the following elements in the same list are children of the node there can be multiple children. If an element of the list is itself a list this starts a new subtree at that position.

Basically what I'm wanting to do is print a binary tree list like this with formatting that makes it easier to read.

A list like this: ['a',['b', 'c', ['d', 'i'], 'e'], 'f', ['g', 'h', ['j', 'k', 'l', 'm']]]

And print it out by level recursively so it looks like this.

a
+---b
    +---c
    +---d
        +---i
    +---e
+---f
+---g
    +---h
    +---j
        +---k
         +---l
         +---m

And here's another example: ['a', ['b', 'c', 'd'], ['e', 'f'], 'g'] Prints out like this:

a
+---b
    +---c
    +---d
+---e
    +---f
+---g

So each child appears on a line with “+---” before the child's value. This string starts directly beneath the parent value. The levels are further indented by 4 extra spaces for each level.

1
  • I can't see an actual Question. What did you try so far? Where exactly did you get stuck?
    – TobiasR.
    May 29, 2015 at 6:10

4 Answers 4

3

Is that what you are after?

lst = ['a', ['b', 'c', ['d', 'i'], 'e'], 'f', ['g', 'h', ['j', 'k', 'l', 'm']]]

def print_list(lst, level=0):
    print('    ' * (level - 1) + '+---' * (level > 0) + lst[0])
    for l in lst[1:]:
        if type(l) is list:
            print_list(l, level + 1)
        else:
            print('    ' * level + '+---' + l)

print_list(lst)

Which gives:

a
+---b
    +---c
    +---d
        +---i
    +---e
+---f
+---g
    +---h
    +---j
        +---k
        +---l
        +---m

And for the second example:

lst = ['a', ['b', 'c', 'd'], ['e', 'f'], 'g']

we get:

a
+---b
    +---c
    +---d
+---e
    +---f
+---g
6
  • That's close to what I want but it's not quite right. I can't seem to post multilne code blocks of what the output should look in a comment so I will post it as an answer so you can see what it should look like. May 29, 2015 at 6:22
  • Just edit your question. Do not post details of your question as an answer. May 29, 2015 at 6:23
  • Ok, I have seen what you suggest, but that goes against the list of lists representation that you linked to yourself. The idea there is that at every level of the list the first element is the parent and the second and third are children. Please describe the actual principle you want to use to create the list representation in your question. May 29, 2015 at 6:30
  • Ahh sorry I meant a tree that can have more than two children per parent not a binary tree. May 29, 2015 at 6:41
  • Ok, quick change to reflect your representation description. May 29, 2015 at 6:47
1
def traverse(t, level=0, indent=4):
    value = t[0]
    if level > 0:
        prefixed_str = ' ' * (indent * (level - 1)) + '+---'
    else:
        prefixed_str = ''
    print prefixed_str + value
    for child in t[1:]:
        traverse(child, level+1)
1
  • The bug is that if you change a node name like 'f' to instead be 'frog' it actually changes the tree structure.
    – cdlane
    Aug 16, 2017 at 8:30
1

A hybrid of the solutions of @satoru and @AndrzejPronobis

def print_tree(tree_or_leaf, level=0):
    head, *tail = tree_or_leaf if isinstance(tree_or_leaf, list) else [tree_or_leaf]

    print('    ' * (level - 1) + '+---' * (level > 0) + head)

    for tree_or_leaf in tail:
        print_tree(tree_or_leaf, level + 1)

print_tree(tree)

With the expected output:

> python3 test.py
a
+---b
    +---c
    +---d
        +---i
    +---e
+---f
+---g
    +---h
    +---j
        +---k
        +---l
        +---m
> 
-1

I made an alteration to the example submitted by Andrzej Pronobis so that a list within a list is the start of a new level instead of the first item being the parent to the remaining items in that list level. This seems easier to read as each open bracket '[' is the start of a sub-level whose parent is the item preceding the open bracket and all siblings and children are contained.

In this example, 'a' and 'f' are at the same level in the hierarchy. 'b', 'c', and 'e' are children of 'a', 'd' and 'i' are children of 'c' and so on.

The code:

lst = ['a', ['b', 'c', ['d', 'i'], 'e'], 'f', ['g', 'h', ['j', 'k', 'l', 'm']]]

def print_list(lst, level = 0):
    for l in lst:
        if type(l) is not list:
            print('    ' * (level - 1) + '+---' * (level > 0) + l)
        elif type(l) is list:
            print_list(l, level + 1)
        else:
            print('    ' * level + '+---' + l)

print_list(lst)

Will produce:

a
+---b
+---c
    +---d
    +---i
+---e
f
+---g
+---h
    +---j
    +---k
    +---l
    +---m
1
  • When I run this on the second example, I don't get the expected result (first example works fine.) Also, you have a if statement that has three clauses, if l is a list, if l isn't a list and an else that should never be reached!
    – cdlane
    Aug 16, 2017 at 8:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.