Andrew Cooke | Contents | Latest | RSS | Previous | Next

C[omp]ute

Welcome to my blog, which was once a mailing list of the same name and is still generated by mail. Please reply via the "comment" links.

Always interested in offers/projects/new ideas. Eclectic experience in fields like: numerical computing; Python web; Java enterprise; functional languages; GPGPU; SQL databases; etc. Based in Santiago, Chile; telecommute worldwide. CV; email.

Personal Projects

Choochoo Training Diary

Last 100 entries

Surprise Paradox; [Books] Good Author List; [Computing] Efficient queries with grouping in Postgres; [Computing] Automatic Wake (Linux); [Computing] AWS CDK Aspects in Go; [Bike] Adidas Gravel Shoes; [Computing, Horror] Biological Chips; [Books] Weird Lit Recs; [Covid] Extended SIR Models; [Art] York-based Printmaker; [Physics] Quantum Transitions are not Instantaneous; [Computing] AI and Drum Machines; [Computing] Probabilities, Stopping Times, Martingales; bpftrace Intro Article; [Computing] Starlab Systems - Linux Laptops; [Computing] Extended Berkeley Packet Filter; [Green] Mainspring Linear Generator; Better Approach; Rummikub Solver; Chilean Poetry; Felicitations - Empowerment Grant; [Bike] Fixing Spyre Brakes (That Need Constant Adjustment); [Computing, Music] Raspberry Pi Media (Audio) Streamer; [Computing] Amazing Hack To Embed DSL In Python; [Bike] Ruta Del Condor (El Alfalfal); [Bike] Estimating Power On Climbs; [Computing] Applying Azure B2C Authentication To Function Apps; [Bike] Gearing On The Back Of An Envelope; [Computing] Okular and Postscript in OpenSuse; There's a fix!; [Computing] Fail2Ban on OpenSuse Leap 15.3 (NFTables); [Cycling, Computing] Power Calculation and Brakes; [Hardware, Computing] Amazing Pockit Computer; Bullying; How I Am - 3 Years Post Accident, 8+ Years With MS; [USA Politics] In America's Uncivil War Republicans Are The Aggressors; [Programming] Selenium and Python; Better Walking Data; [Bike] How Fast Before Walking More Efficient Than Cycling?; [COVID] Coronavirus And Cycling; [Programming] Docker on OpenSuse; Cadence v Speed; [Bike] Gearing For Real Cyclists; [Programming] React plotting - visx; [Programming] React Leaflet; AliExpress Independent Sellers; Applebaum - Twilight of Democracy; [Politics] Back + US Elections; [Programming,Exercise] Simple Timer Script; [News] 2019: The year revolt went global; [Politics] The world's most-surveilled cities; [Bike] Hope Freehub; [Restaurant] Mama Chau's (Chinese, Providencia); [Politics] Brexit Podcast; [Diary] Pneumonia; [Politics] Britain's Reichstag Fire moment; install cairo; [Programming] GCC Sanitizer Flags; [GPU, Programming] Per-Thread Program Counters; My Bike Accident - Looking Back One Year; [Python] Geographic heights are incredibly easy!; [Cooking] Cookie Recipe; Efficient, Simple, Directed Maximisation of Noisy Function; And for argparse; Bash Completion in Python; [Computing] Configuring Github Jekyll Locally; [Maths, Link] The Napkin Project; You can Masquerade in Firewalld; [Bike] Servicing Budget (Spring) Forks; [Crypto] CIA Internet Comms Failure; [Python] Cute Rate Limiting API; [Causality] Judea Pearl Lecture; [Security, Computing] Chinese Hardware Hack Of Supermicro Boards; SQLAlchemy Joined Table Inheritance and Delete Cascade; [Translation] The Club; [Computing] Super Potato Bruh; [Computing] Extending Jupyter; Further HRM Details; [Computing, Bike] Activities in ch2; [Books, Link] Modern Japanese Lit; What ended up there; [Link, Book] Logic Book; Update - Garmin Express / Connect; Garmin Forerunner 35 v 230; [Link, Politics, Internet] Government Trolls; [Link, Politics] Why identity politics benefits the right more than the left; SSH Forwarding; A Specification For Repeating Events; A Fight for the Soul of Science; [Science, Book, Link] Lost In Math; OpenSuse Leap 15 Network Fixes; Update; [Book] Galileo's Middle Finger; [Bike] Chinese Carbon Rims; [Bike] Servicing Shimano XT Front Hub HB-M8010; [Bike] Aliexpress Cycling Tops; [Computing] Change to ssh handling of multiple identities?; [Bike] Endura Hummvee Lite II; [Computing] Marble Based Logic; [Link, Politics] Sanity Check For Nuclear Launch; [Link, Science] Entropy and Life

© 2006-2017 Andrew Cooke (site) / post authors (content).

Printing binary trees sideways

From: andrew cooke <andrew@...>

Date: Mon, 13 May 2013 11:16:42 -0400

This was preliminary work for the StackOverflow answer at
http://stackoverflow.com/questions/11096134/print-a-binary-tree-on-its-side/16680023#16680023
- I did it while on holiday (installed Python on Mum's laptop :o) and then
posted the answer when I got home.  I have modified these posts since first
writing them to improve the code and explanation a little.

To be honest, it's not very exciting code - just careful bookkeeping and the
kind of recursive approach you'd expect, merging results from sub-trees.

Here are some results (I've named the leaves according to their location,
which helps understand what is happening, I hope):

 5 nodes
    /rr
   /\rl
  / /lrr
  \/\lrl
   \ll

 20 nodes
	    /rrrrr
	   /\rrrrl
	  /\rrrl
	 /\/rrlr
	/  \rrll
       /   /rlrrr
      /\  /\/rlrrlr
     /  \/\ \rlrrll
    /    \ \rlrl
   /      \/rllr
  /        \rlll
  \        /lrrrr
   \      /\lrrrl
    \    /\lrrl
     \  / /lrlr
      \/\/ /lrllrr
       \ \/\lrllrl
	\ \lrlll
	 \/llr
	  \lll

And the code follows.

Andrew



#!/usr/local/bin/python3.3

from itertools import chain
from random import randint


# first, some support routines.  these assume that a tree is either a string
# leaf value, or a tuple (pair) of subnodes.

def leaf(t):
    '''is the given node a leaf?'''
    return isinstance(t, str)

def random(n):
    '''generate a random tree with n nodes (n > 1)'''
    def extend(t):
        if leaf(t):
            return (t+'l', t+'r')
        else:
            l, r = t
            if randint(0, 1): return (l, extend(r))
            else: return (extend(l), r)
    t = ''
    for _ in range(n-1): t = extend(t)
    return t


# next, the formatting itself.  this is not that exciting - a recursive 
# descent to the leaves and then a merging of sub-trees on the returns.
# the hard part is just the book-keeping.

def format(t):
    '''format the tree (returns a multi-line string reprn)'''

    def pad(label, prefix, spaces, previous):
        '''add spaces between / (or \) and the previous line contents.
           change ' ' to label to see what logic is used where'''
        return prefix + (' ' * spaces) + previous

    def merge(l, r):
        '''merges the two sub-trees to generate the fragment for the
           combined node.  a fragment is (above, below, lines) where
           above is number of lines above root, below below root, and
           lines is an iterator over each partial line.'''
        l_above, l_below, l_lines = l
        r_above, r_below, r_lines = r
        gap = r_below + l_above
        gap_above = l_above  # this balances the result (see post text)
        gap_below = gap - gap_above

        def lines():
            '''the actual mergin of lines.  there are six different cases,
               handled in turn.'''
            for (i, line) in enumerate(chain(r_lines, l_lines)):
                if i < r_above:
                    # we already have 'sloped' data above where we are joining
                    yield line
                elif i - r_above < gap_above:
                    # we are in the upper branch region, joined by a / symbol
                    if i < r_above + r_below:
                        # are we filling the increasing gap between the new 
                        # / branch and the existing tree that has a \ shaped 
                        # boundary?
                        yield pad('A', '/', 2 * (i - r_above), line)
                    else:
                        # or are we in the constant sized gap between the 
                        # new / branch and the upper / shaped boundary of the 
                        # lower sub-node?
                        yield pad('B', '/', 2 * gap_below - 1, line)
                elif i - r_above - gap_above < gap_below:
                    # we are in the lower branch region, joined by a \ symbol
                    if i < r_above + r_below:
                        # are we overlapping the \ shaped boundary of the 
                        # upper sub-node?
                        yield pad('C', '\\', 2 * gap_above - 1, line)
                    else:
                        # or are we in the gap between the new \ and the 
                        # / shaped edge of the lower sub-node?
                        spaces = 2 * (r_above + gap_above + gap_below - i - 1)
                        yield pad('D', '\\', spaces, line)
                else:
                    # we already ave 'sloped' data below where we are joining
                    yield line
        return (r_above + gap_above, gap_below + l_below, lines())

    def descend(left, t):
        '''descend to leaf nodes, where we know what the fragments are
           (just the leaf contents) and then merge nodes on return.'''
        if leaf(t):
            if left:
                return (1, 0, [t])
            else:
                return (0, 1, [t])
        else:
            l, r = t
            return merge(descend(True, l), descend(False, r))

    def flatten(t):
        '''add left-hand spacing to the final tree.'''
        above, below, lines = t
        for (i, line) in enumerate(lines):
            if i < above: yield (' ' * (above - i - 1)) + line
            else: yield (' ' * (i - above)) + line

    # put it all together...
    return '\n'.join(flatten(descend(True, t)))


if __name__ == '__main__':
    for n in range(1,20,3):
        tree = random(n)
        print(tree)
        print(format(tree))

Some explanation

From: andrew cooke <andrew@...>

Date: Mon, 13 May 2013 11:45:05 -0400

[This post has also been edited since first posting]


The tree is formatted in three steps.


First, there's a recursive descent to the nodes, in the function descent.
This tracks whether the immediately preceding branch was left or right, so
that we know how to start the node (effectively, with a / or a \).


Second, as that function returns for each pair of nodes, we call "merge" to
combine the formatting information for the two sub-nodes.  To understand merge
you need to first understand what the formatting information is: a tuple
containing (above, below, lines) where above is the number of lines above the
root (of this sub-tree) and below is the number of lines below (note that a
root is always between lines).  Then lines is a sequence of strings containing
the existing information for each line.

The only unusual thing here, really, is that the lines are stored without
initial padding (that's what "flatten" adds, right at the end).  We need to do
this because if we stored them as padded blocks then we'd need to modify the
existing contents - storing without padding avoids needing to mutate data.

Here's an example.  Consider the tree

 /r
 \/lr
  \ll

That would be stored as (1, 2, ['/r', '\/lr', '\ll']) (I am not escaping
backslashes here!).  There is no whitespace padding to the left of those
lines.

Then merge is simply patching together the lines from the two subtrees while
adding some extra / and \ characters and spaces.  It's only complicated
because of fiddly details - there's no deep magic.  See the comments in the
code.

You can get an idea of which logic is used where by changing the "pad" routine
to print labels instead of spaces:

	  /rrrr
	 /\/rrrlr
	/\C\rrrll
       /AA\rrl
      /BBB/rlrrr
     /\DD/\rlrrl
    /AA\/\rlrl
   /AAAA\/rllr
  /AAAAAA\rlll
  \DDDDDD/lrrr
   \DDDD/\/lrrlr
    \DD/\C\lrrll
     \/AA\/lrlr
      \CCC\lrll
       \DD/llrr
	\/\/llrlr
	 \C\llrll
	  \/lllr
	   \llll

Compare the letters A-D with those in the merge routine.


Third, flatten adds space padding as needed for the final result (see above).


If you work through the code you'll see that there's an arbitrary decision
about exactly how to join the two subtrees - you get to choose the relative
number of / and \ characters (their sum is fixed).  The current code uses more
characters to get to the smaller subtree, so that the final result is
compact.  The line is:

  gap_above = l_above

And I'll try show what that means in this diagram:

     /rr
    X\/rlr
   X  \rll
  X   Ylrrr
  \  Y\lrrl
   \Y\lrl
    \ll

Here X is "gap_above" and Y is "labove".  The "gap" is the number of lines
between the two sub-node roots that are being merged.  "gap_above" is the
upper branch (the / shaped part).  "l" identifies the lefthand sub-node and
"above" is the number of lines above the root.  So I choose the number of Xs
to match the number of Ys.


Also, for trees with data in the nodes (as well as the leaves) see
http://www.acooke.org/cute/ASCIIDispl0.html

Andrew

Comment on this post