Created
October 28, 2016 03:17
-
-
Save gweakliem/41392dad136fcb11bb3f3d347d3991d3 to your computer and use it in GitHub Desktop.
Another take at the IntTree using something like S-Expressions.
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
'''Tree representing | |
1 | |
/|\ | |
2 3 4 | |
/\ |\ | |
5 6 9 11 | |
/\ \ | |
7 8 10 | |
Not especially happy with this. Feels like I'm fighting the representation. | |
''' | |
# encoding for tree above as S-Expression | |
test_input = '1(2(5 6(7 8))3 4(9(10)11))' | |
class Node(): | |
def __init__(self, value): | |
self.children = [] | |
self.value = value | |
def __str__(self): | |
return "%s - %s" % (self.value, str(self.children)) | |
def __repr__(self): | |
return "(%r,%r)" % (self.value,self.children) | |
def parse_tree(field_gen): | |
next_node = Node('') | |
new_nodes = [] | |
node_completed = False | |
while True: | |
try: | |
op = next(field_gen)[1] | |
if op == '(': | |
next_node.children = parse_tree(field_gen) | |
new_nodes.append(next_node) | |
next_node = Node('') | |
elif op == ')': | |
if next_node.value != '': | |
new_nodes.append(next_node) | |
return new_nodes | |
elif op == ' ': | |
if next_node.value != '': | |
node_completed = True | |
new_nodes.append(next_node) | |
else: | |
if node_completed: | |
next_node = Node('') | |
next_node.value += op | |
except StopIteration: | |
if next_node != None: | |
new_nodes.append(next_node) | |
return new_nodes | |
def write_tree(tree): | |
result = str(tree.value) | |
if len(tree.children) > 0: | |
result += '(' | |
for i,c in enumerate(tree.children): | |
if len(c.children) > 0: | |
result += write_tree(c) | |
else: | |
result += str(c.value) | |
if i < (len(tree.children)-1): | |
result += ' ' | |
result += ')' | |
return result | |
def main(): | |
tree = parse_tree(enumerate(test_input)) | |
#print("%r" % (tree)) | |
test_output = write_tree(tree[0]) | |
print(test_output) | |
again = parse_tree(enumerate(test_output)) | |
#print("%r" % (again)) | |
# now test reflexivity | |
print(write_tree(again[0])) | |
#if __name__ == "__main__": | |
main() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment