Kristof Pal
Kristof Pal

Reputation: 1026

Printing a Tree data structure in Python

I was looking for a possible implementation of tree printing, which prints the tree in a user-friendly way, and not as an instance of object.

I came across this solution on the net:

Source: http://cbio.ufs.ac.za/live_docs/nbn_tut/trees.html

class node(object):
    def __init__(self, value, children = []):
        self.value = value
        self.children = children

    def __repr__(self, level=0):
        ret = "\t"*level+repr(self.value)+"\n"
        for child in self.children:
            ret += child.__repr__(level+1)
        return ret

This code prints the tree in the following way:

'grandmother'
    'daughter'
        'granddaughter'
        'grandson'
    'son'
        'granddaughter'
        'grandson'

Is it possible to have the same result but without changing the __repr__ method, because I am using it for another purpose.

Upvotes: 30

Views: 105150

Answers (4)

PierreGtch
PierreGtch

Reputation: 61

A simple solution to print pathlib.Path objects:

from pathlib import Path

def print_tree(p: Path, last=True, header=''):
    elbow = "└──"
    pipe = "│  "
    tee = "├──"
    blank = "   "
    print(header + (elbow if last else tee) + p.name)
    if p.is_dir():
        children = list(p.iterdir())
        for i, c in enumerate(children):
            print_tree(c, header=header + (blank if last else pipe), last=i == len(children) - 1)

print_tree(Path("./MNE-001-2014-bids-cache"))

Output:

└──MNE-001-2014-bids-cache
   ├──sub-1
   │  ├──ses-E
   │  │  ├──sub-1_ses-E_scans.tsv
   │  │  └──eeg
   │  │     ├──sub-1_ses-E_task-imagery_run-5_desc-b3b3d5ec2913316a996cc197966c5862_events.tsv
   │  │     ├──sub-1_ses-E_space-CapTrak_electrodes.tsv
   │  │     ├──sub-1_ses-E_task-imagery_run-0_desc-b3b3d5ec2913316a996cc197966c5862_eeg.json
   │  │     ├──sub-1_ses-E_task-imagery_run-1_desc-b3b3d5ec2913316a996cc197966c5862_eeg.edf
   │  │     └──sub-1_ses-E_task-imagery_run-2_desc-b3b3d5ec2913316a996cc197966c5862_channels.tsv
   │  ├──sub-1_desc-b3b3d5ec2913316a996cc197966c5862_lockfile.json
   │  └──ses-T
   │     ├──sub-1_ses-T_scans.tsv
   │     └──eeg
   │        ├──sub-1_ses-T_task-imagery_run-3_desc-b3b3d5ec2913316a996cc197966c5862_eeg.json
   │        ├──sub-1_ses-T_task-imagery_run-3_desc-b3b3d5ec2913316a996cc197966c5862_eeg.edf
   │        ├──sub-1_ses-T_task-imagery_run-0_desc-b3b3d5ec2913316a996cc197966c5862_events.tsv
   │        └──sub-1_ses-T_task-imagery_run-4_desc-b3b3d5ec2913316a996cc197966c5862_eeg.edf
   ├──README
   ├──dataset_description.json
   ├──participants.json
   └──participants.tsv

Upvotes: 6

vvvvv
vvvvv

Reputation: 31640

Solution without modifying __repr__ and __str__

def other_name(self, level=0):
    print('\t' * level + repr(self.value))
    for child in self.children:
        child.other_name(level + 1)

This answer was posted as an edit to the question Printing a Tree data structure in Python by the OP Kristof Pal under CC BY-SA 3.0.

Upvotes: 0

Rambatino
Rambatino

Reputation: 4914

Why don't you store it as a treelib object and print it out similar to how we print the CHAID tree out here with more relevant node descriptions related to your use case?

([], {0: 809, 1: 500}, (sex, p=1.47145310169e-81, chi=365.886947811, groups=[['female'], ['male']]))
├── (['female'], {0: 127, 1: 339}, (embarked, p=9.17624191599e-07, chi=24.0936494474, groups=[['C', '<missing>'], ['Q', 'S']]))
│   ├── (['C', '<missing>'], {0: 11, 1: 104}, <Invalid Chaid Split>)
│   └── (['Q', 'S'], {0: 116, 1: 235}, <Invalid Chaid Split>)
└── (['male'], {0: 682, 1: 161}, (embarked, p=5.017855245e-05, chi=16.4413525404, groups=[['C'], ['Q', 'S']]))
    ├── (['C'], {0: 109, 1: 48}, <Invalid Chaid Split>)
    └── (['Q', 'S'], {0: 573, 1: 113}, <Invalid Chaid Split>)

Upvotes: 6

Martijn Pieters
Martijn Pieters

Reputation: 1121992

Yes, move the __repr__ code to __str__, then call str() on your tree or pass it to the print statement. Remember to use __str__ in the recursive calls too:

class node(object):
    def __init__(self, value, children = []):
        self.value = value
        self.children = children

    def __str__(self, level=0):
        ret = "\t"*level+repr(self.value)+"\n"
        for child in self.children:
            ret += child.__str__(level+1)
        return ret

    def __repr__(self):
        return '<tree node representation>'

Demo:

>>> root = node('grandmother')
>>> root.children = [node('daughter'), node('son')]
>>> root.children[0].children = [node('granddaughter'), node('grandson')]
>>> root.children[1].children = [node('granddaughter'), node('grandson')]
>>> root
<tree node representation>
>>> str(root)
"'grandmother'\n\t'daughter'\n\t\t'granddaughter'\n\t\t'grandson'\n\t'son'\n\t\t'granddaughter'\n\t\t'grandson'\n"
>>> print root
'grandmother'
    'daughter'
        'granddaughter'
        'grandson'
    'son'
        'granddaughter'
        'grandson'

Upvotes: 42

Related Questions