Skip to content

Instantly share code, notes, and snippets.

@lucarin91
Last active August 16, 2017 16:49
Show Gist options
  • Save lucarin91/db5c1f0c1b1678eb9010088aea8f4b91 to your computer and use it in GitHub Desktop.
Save lucarin91/db5c1f0c1b1678eb9010088aea8f4b91 to your computer and use it in GitHub Desktop.
Tree visit made using yield and new from keywords of python 3
from pprint import PrettyPrinter
from random import randrange
def post_order(t, deep=0):
if isinstance(t, dotdict):
# is a node
yield deep, t.value
yield from post_order(t.left, deep+1)
yield from post_order(t.right, deep+1)
else:
# is a leaf
yield deep, t
def in_order(t, deep=0):
if isinstance(t, dotdict):
# is a node
yield from in_order(t.left, deep+1)
yield deep, t.value
yield from in_order(t.right, deep+1)
else:
# is a leaf
yield deep, t
def pre_order(t, deep=0):
if isinstance(t, dotdict):
# is a node
yield from pre_order(t.left, deep+1)
yield from pre_order(t.right, deep+1)
yield deep, t.value
else:
# is a leaf
yield deep, t
def main():
tree = dotdict({
'value': randrange(100),
'left': dotdict({
'value': randrange(100),
'left': dotdict({
'value': randrange(100),
'left': randrange(100),
'right': randrange(100)
}),
'right': randrange(100)
}),
'right': dotdict({
'value': randrange(100),
'left': randrange(100),
'right': dotdict({
'value': randrange(100),
'left': randrange(100),
'right': randrange(100)
}),
})
})
pp = PrettyPrinter(indent=2)
pp.pprint(tree)
print('\nIN-ORDER VISIT')
for deep, item in in_order(tree):
print('deep:{} value:{}'.format(deep, item))
print('\nPOST-ORDER VISIT')
for deep, item in post_order(tree):
print('deep:{} value:{}'.format(deep, item))
print('\nPRE-ORDER VISIT')
for deep, item in pre_order(tree):
print('deep:{} value:{}'.format(deep, item))
class dotdict(dict):
"""dot.notation access to dictionary attributes"""
__getattr__ = dict.get
__setattr__ = dict.__setitem__
__delattr__ = dict.__delitem__
if __name__ == '__main__':
main()
@sn1p3r46
Copy link

sn1p3r46 commented Aug 16, 2017

class dotdict(dict):
    """dot.notation access to dictionary attributes"""
    __getattr__ = dict.get
    __setattr__ = dict.__setitem__
    __delattr__ = dict.__delitem__

Coolest thing ever!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment