Last active
August 25, 2018 08:02
-
-
Save JustinSDK/c811a413a4ef6dda972fe09465f94e61 to your computer and use it in GitHub Desktop.
Byte Code ABC - 1
This file contains 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 Num: | |
def __init__(self, value): | |
self.value = value | |
def evaluate(self, stack): | |
push(stack, self.value) | |
return stack | |
class Add: | |
def __init__(self, left, right): | |
self.left = left | |
self.right = right | |
def evaluate(self, stack): | |
self.left.evaluate(stack) | |
self.right.evaluate(stack) | |
add(stack) | |
return stack | |
class Mul: | |
def __init__(self, left, right): | |
self.left = left | |
self.right = right | |
def evaluate(self, stack): | |
self.left.evaluate(stack) | |
self.right.evaluate(stack) | |
mul(stack) | |
return stack | |
# Byte Code Instructions | |
def push(stack, value): | |
stack.append(value) | |
def add(stack): | |
r = stack.pop() | |
l = stack.pop() | |
stack.append(l + r) | |
def mul(stack): | |
r = stack.pop() | |
l = stack.pop() | |
stack.append(l * r) | |
# 1 + 2 | |
print(Add(Num(1), Num(2)).evaluate([])) | |
# 1 + 2 + 3 | |
print(Add(Add(Num(1), Num(2)), Num(3)).evaluate([])) | |
# 5 + 2 * 3 | |
print(Add(Num(5), Mul(Num(2), Num(3))).evaluate([])) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment