Last active
March 4, 2020 20:51
-
-
Save onelharrison/f7cd8b95b43eaabf861eee8889bc1015 to your computer and use it in GitHub Desktop.
Coding Trees in Python 3 (https://www.youtube.com/watch?v=7tCNu4CnjVc)
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
class Expr: | |
def eval(self, env): | |
raise NotImplementedError | |
class BinaryOperator(Expr): | |
def __init__(self, left, right): | |
super().__init__() | |
self.left = left | |
self.right = right | |
def __str__(self): | |
return f'({self.left} {self.operator} {self.right})' | |
class Times(BinaryOperator): | |
def __init__(self, left, right): | |
super().__init__(left, right) | |
self.operator = '*' | |
def eval(self, env): | |
return self.left.eval(env) * self.right.eval(env) | |
class Plus(BinaryOperator): | |
def __init__(self, left, right): | |
super().__init__(left, right) | |
self.operator = '+' | |
def eval(self, env): | |
return self.left.eval(env) + self.right.eval(env) | |
class Minus(BinaryOperator): | |
def __init__(self, left, right): | |
super().__init__(left, right) | |
self.operator = '-' | |
def eval(self, env): | |
return self.left.eval(env) - self.right.eval(env) | |
class Divide(BinaryOperator): | |
def __init__(self, left, right): | |
super().__init__(left, right) | |
self.operator = '/' | |
def eval(self, env): | |
return self.left.eval(env) / self.right.eval(env) | |
class Const(Expr): | |
def __init__(self, val): | |
self.val = val | |
def __str__(self): | |
return str(self.val) | |
def eval(self, _env): | |
return self.val | |
class Var(Expr): | |
def __init__(self, name): | |
self.name = name | |
def __str__(self): | |
return self.name | |
def eval(self, _env): | |
return env[self.name] | |
e1 = Times(Const(3), Plus(Var('x'), Var('y'))) | |
print(e1) | |
e2 = Plus(Times(Const(3), Var('y')), Var('x')) | |
print(e2) | |
env = { 'x': 2, 'y': 4 } | |
print(e1.eval(env)) | |
print(e2.eval(env)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment