Created
August 1, 2014 01:07
-
-
Save lelandbatey/f2dd1a99930a42ec91ce to your computer and use it in GitHub Desktop.
Prints a perfect binary tree of given height, just for fun : )
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
#!/usr/bin/python | |
# -*- coding: utf-8 -*- | |
from __future__ import print_function | |
import sys | |
IS_TERM=False | |
if sys.stdout.isatty(): | |
IS_TERM = True | |
if IS_TERM: | |
left_corner = '┌' | |
right_corner = '┐' | |
fill = '─' | |
else: | |
left_corner = '=' | |
right_corner = '=' | |
fill = '=' | |
def print_line(sbuff, seperator, nodes): | |
print(' '*sbuff,end='') | |
print((' '*seperator).join(nodes), end='') | |
print(' '*sbuff) | |
def print_tree(height=5): | |
for step in range(height): | |
# Extra subtraction for further shrinkage | |
level = height - step - 1 | |
sideBuffer = (2**level)-1 | |
seperator = (2**(level+1) )-1 | |
nodes = ['O']*(2**step) | |
pillars = ['|']*(2**step) | |
if step: | |
print(' '*sideBuffer,end='') | |
for x in range(2**step): | |
if x%2: | |
print(right_corner,end='') | |
print(' '*seperator,end='') | |
else: | |
print(left_corner,end='') | |
print(fill*seperator,end='') | |
print(' '*sideBuffer) | |
print_line(sideBuffer,seperator, pillars) | |
print_line(sideBuffer, seperator, nodes) | |
if __name__ == '__main__': | |
if len(sys.argv) > 1: | |
print_tree(int(sys.argv[1])) | |
else: | |
print_tree(6) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment