Skip to content

Instantly share code, notes, and snippets.

@eserge
Created July 30, 2017 13:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eserge/4c378e63a67dff0e728d1fdf5b24022e to your computer and use it in GitHub Desktop.
Save eserge/4c378e63a67dff0e728d1fdf5b24022e to your computer and use it in GitHub Desktop.
# starting with https://www.codewars.com/kata/stack-arithmetic-machine/train/python
import operator
class Machine(object):
def __init__(self, cpu):
self.cpu = cpu
def execute(self, instr):
iterative_operations = [
'add', 'sub', 'mul', 'div',
]
instruction, operands = instr.split(' ', 1)
if instruction == 'push':
self.push(int(operands))
elif instruction in iterative_operations:
self.iterative_stack_operation(instruction, int(operands))
def push(self, value):
self.cpu.write_stack(value)
def binary_stack_operation(self, operation):
self.cpu.write_stack(
operation(
self.cpu.pop_stack(),
self.cpu.pop_stack()
)
)
def iterative_stack_operation(self, instruction, count, register_name=None):
operators_mapping = {
'add': operator.add,
'sub': operator.sub,
'mul': operator.mul,
'div': operator.floordiv,
}
if count < 2:
return
for _ in range(count - 1):
self.binary_stack_operation(
operators_mapping[instruction]
)
register_name = register_name or 'a'
self.cpu.write_reg(register_name, self.cpu.pop_stack())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment