Skip to content
Snippets Groups Projects
Commit 2289c465 authored by Martin Mareš's avatar Martin Mareš
Browse files

Výrazy: Příklad se stromečky

parent f3921c69
No related branches found
No related tags found
No related merge requests found
#!/usr/bin/python3
class Node:
def __init__(self, op, left=None, right=None):
self.op = op # Buď číslo nebo jméno operátoru
self.left = left
self.right = right
def __str__(self):
if type(self.op) is int:
return str(self.op)
else:
return '(' + str(self.left) + self.op + str(self.right) + ')'
def print_tree(self, level=0):
if self.right is not None:
self.right.print_tree(level+1)
print(" "*level, self.op)
if self.left is not None:
self.left.print_tree(level+1)
def eval(self):
op = self.op
if type(op) is int:
return self.op
else:
l = self.left.eval()
r = self.right.eval()
if op == '+':
return l + r
if op == '-':
return l - r
if op == '*':
return l * r
if op == '/':
return l // r
raise NotImplemented()
x = Node('+', Node('*', Node(3), Node(4)), Node('-', Node(5), Node(6)))
print(x)
# x.print_tree()
# print(x.eval())
# Další úkoly:
# - doplnit unární operátory (třeba 'N' pro negaci)
# - počítání hloubky stromu
# - výpis stromu v postfixovém tvaru
# - převod postfixového tvaru na strom
# - výpis stromu v infixovém tvaru bez zbytečných závorek
# - prevod infixového tvaru na strom (*)
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment