Visualize a tree: Difference between revisions

Content added Content deleted
(→‎{{header|Python}}: Plain text tree variant (functional composition))
Line 1,814: Line 1,814:
[[File:display_tree.png|900px]]
[[File:display_tree.png|900px]]
=={{header|Python}}==
=={{header|Python}}==
===Library module===
Python has the [http://www.doughellmann.com/PyMOTW/pprint/ pprint] [http://docs.python.org/py3k/library/pprint.html module] for pretty-printing data.
Python has the [http://www.doughellmann.com/PyMOTW/pprint/ pprint] [http://docs.python.org/py3k/library/pprint.html module] for pretty-printing data.


Line 1,971: Line 1,972:
('C1', 'C2', ('D1', 'E', 'D2', 'D3'), 'C3'))]
('C1', 'C2', ('D1', 'E', 'D2', 'D3'), 'C3'))]
>>> </lang>
>>> </lang>


===Functional composition===
<lang python>from operator import (add)
import itertools


# draw :: Tree String -> [String]
def draw(node):
def shift(first, other, xs):
return list(itertools.starmap(
add,
zip(
[first] + list(itertools.repeat(other, len(xs) - 1)),
xs
)
))

def drawSubTrees(xs):
lng = len(xs)
return (
(
['|'] + shift(
'├─ ', '│ ', draw(xs[0])
) + drawSubTrees(xs[1:])
) if 1 < lng else ['|'] + shift('└─ ', ' ', draw(xs[0]))
) if 0 < lng else []

return (str(node['root'])).splitlines() + drawSubTrees(node['nest'])


# TEST ----------------------------------------------------

tree = {'nest':
[{'nest': [{'nest': [], 'root': 'gamma', 'type': 'Node'},
{'nest': [], 'root': 'epsilon', 'type': 'Node'},
{'nest': [], 'root': 'eta', 'type': 'Node'}],
'root': 'beta',
'type': 'Node'},
{'nest': [{'nest': [], 'root': 'kappa', 'type': 'Node'},
{'nest': [], 'root': 'mu', 'type': 'Node'},
{'nest': [], 'root': 'xi', 'type': 'Node'}],
'root': 'iota',
'type': 'Node'},
{'nest': [{'nest': [], 'root': 'rho', 'type': 'Node'},
{'nest': [], 'root': 'tau', 'type': 'Node'},
{'nest': [], 'root': 'phi', 'type': 'Node'}],
'root': 'pi',
'type': 'Node'}],
'root': 'alpha',
'type': 'Node'}
print(
'\n'.join(draw(tree))
)</lang>
{{Out}}
<pre>alpha
|
├─ beta
│ |
│ ├─ gamma
│ |
│ ├─ epsilon
│ |
│ └─ eta
|
├─ iota
│ |
│ ├─ kappa
│ |
│ ├─ mu
│ |
│ └─ xi
|
└─ pi
|
├─ rho
|
├─ tau
|
└─ phi</pre>


=={{header|Racket}}==
=={{header|Racket}}==