From 2289c465c3d796db057b9ae07f7253f10cf3bfa2 Mon Sep 17 00:00:00 2001 From: Martin Mares <mj@ucw.cz> Date: Wed, 8 Apr 2020 09:41:49 +0200 Subject: [PATCH] =?UTF-8?q?V=C3=BDrazy:=20P=C5=99=C3=ADklad=20se=20strome?= =?UTF-8?q?=C4=8Dky?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- 06-vyrazy/strom-vyrazu.py | 52 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100755 06-vyrazy/strom-vyrazu.py diff --git a/06-vyrazy/strom-vyrazu.py b/06-vyrazy/strom-vyrazu.py new file mode 100755 index 0000000..d51cf03 --- /dev/null +++ b/06-vyrazy/strom-vyrazu.py @@ -0,0 +1,52 @@ +#!/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 (*) -- GitLab