Created
February 21, 2015 19:32
-
-
Save mh-github/f177adfb53b222a4899a to your computer and use it in GitHub Desktop.
# Dendrogram drawing (Python recipe) from http://code.activestate.com/recipes/139422-dendrogram-drawing/ def printDendrogram(T, sep=3): """Print dendrogram of a binary tree. Each tree node is represented by a length-2 tuple.""" def isPair(T): return type(T) == tuple and len(T) == 2 def maxHeight(T): if isPair(T): h = max(maxHeight(T[0]), maxHeig…
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # Dendrogram drawing (Python recipe) from http://code.activestate.com/recipes/139422-dendrogram-drawing/ | |
| def printDendrogram(T, sep=3): | |
| """Print dendrogram of a binary tree. Each tree node is represented by a length-2 tuple.""" | |
| def isPair(T): | |
| return type(T) == tuple and len(T) == 2 | |
| def maxHeight(T): | |
| if isPair(T): | |
| h = max(maxHeight(T[0]), maxHeight(T[1])) | |
| else: | |
| h = len(str(T)) | |
| return h + sep | |
| activeLevels = {} | |
| def traverse(T, h, isFirst): | |
| if isPair(T): | |
| traverse(T[0], h-sep, 1) | |
| s = [' ']*(h-sep) | |
| s.append('|') | |
| else: | |
| s = list(str(T)) | |
| s.append(' ') | |
| while len(s) < h: | |
| s.append('-') | |
| if (isFirst >= 0): | |
| s.append('+') | |
| if isFirst: | |
| activeLevels[h] = 1 | |
| else: | |
| del activeLevels[h] | |
| A = list(activeLevels) | |
| A.sort() | |
| for L in A: | |
| if len(s) < L: | |
| while len(s) < L: | |
| s.append(' ') | |
| s.append('|') | |
| print (''.join(s)) | |
| if isPair(T): | |
| traverse(T[1], h-sep, 0) | |
| traverse(T, maxHeight(T), -1) | |
| printDendrogram( ( ( ( 'a' , 'b') , 'c'), ( ( 'd' , 'e' ), ( 'f', 'g' ) ) ) ) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment