The Stack Arithmetic Machine
---------------------------

This time we're going to be writing a stack arithmetic machine, and we're going to call it Sam. Essentially, Sam is a very small virtual machine, with a simple intruction set, four general registers, and a stack. We've already given a CPU class, which gives you read and write access to registers and the stack, through `readReg()` and `writeReg()`, and `popStack()` and `writeStack()` respectively. All instructions on Sam are 32-bit (Java int), and either interact with the stack, or one of the 4 registers; `a`, `b`, `c`, or `d`.

The CPU API
-----------

The CPU instructions available through the CPU class, with a bit more detail:

```python
read_reg(self, name): Returns the value of the named register.
write_reg(self, name, value): Stores the value into the given register.

pop_stack(self): Pops the top element of the stack, returning the value.
write_stack(self, value): Pushes an element onto the stack.
```

Note that the registers have a default value of `0` and  that the sStack is printable (if needed).



The Instruction Set
-------------------

Instructions for same are done in assembly style, and are passed one by one into the `Exec|exec|execute` function (depending on your language). Each instruction begins with the name of the operation, and is optionally followed by either one or two operands. The operands are marked in the table below by either `[reg]`, which accepts a register name, or `[reg|int]` which accepts either a register, or an immediate integer value.

### Stack Operations

```
push [reg|int]: Pushes a register [reg] or an immediate value [int] to the stack.

pop: Pops a value of the stack, discarding the value.

pop [reg]: Pops a value of the stack, into the given register [reg].

pushr: Pushes the general registers onto the stack, in order. (a, b, c, d)

pushrr: Pushes the general registers onto the stack, in reverse order. (d, c, b, a)

popr: Pops values off the stack, and loads them into the general registers, in order so that the two executions `pushr()`  and `popr()` would leave the registers unchanged.

poprr: Pops values off the stack, and loads them into the general registers, in order so that the two executions `pushr()`  and `poprr()` would invert the values of the registers from left to right.
```

### Misc Operations

```
mov [reg|int], [reg2]: Stores the value from [reg|int] into the register [reg2].
```

### Arithmetic Operations

```
add [reg|int]: Pops [reg|int] arguments off the stack, storing the sum in register a.

sub [reg|int]: Pops [reg|int] arguments off the stack, storing the difference in register a.

mul [reg|int]: Pops [reg|int] arguments off the stack, storing the product in register a.

div [reg|int]: Pops [reg|int] arguments off the stack, storing the quotient in register a.

and [reg|int]: Pops [reg|int] arguments off the stack, performing a bit-and operation, and storing the result in register a.

or [reg|int] : Pops [reg|int] arguments off the stack, performing a bit-or operation, and storing the result in register a.

xor [reg|int]: Pops [reg|int] arguments off the stack, performing a bit-xor operation, and storing the result in register a.
```

All arithmetic operations have 4 variants; they may be suffixed with the character `'a'` (`adda`, `xora`), and they may take an additional register parameter, which is the destination register. Thus, using add as an example:
```
add 5: Adds the top 5 values of the stack, storing the result in register a.

add 5, b: Adds the top 5 values of the stack, storing the result in register b instead.

adda 5: Pushes the value of register A onto the stack, then adds the top 5 values of the stack, and stores the result in register a.

adda 5, b: Pushes the value of register A onto the stack, adds the top 5 values of the stack, and stores the result in register b.
```

All arithmetic instructions may also take a register as their first argument, to perform a variable number of operation, as follows:
```
mov 3, a: Stores the number 3 in register a.
add a: Adds the top a values of the stack (in this case 3), storing the result in register a.
```

Difficulty: MEDIUM

Starter code:
def __init__(self, cpu):
	

Solutions:
from operator import add, sub, mul, floordiv as div, and_, or_, xor
OP = {'add': add, 'sub': sub, 'mul': mul, 'div': div, 'and': and_, 'or': or_, 'xor': xor}

class Machine(object):

	def __init__(self, cpu):
		self.cpu = cpu

	def execute(self, instruction):
		(cmd, a, b) = (instruction.replace(',', ' ') + ' 0 0').split()[:3]
		v = self.cpu.read_reg(a) if a in 'abcd' else int(a)
		if cmd == 'mov':
			self.cpu.write_reg(b, v)
		elif cmd == 'pop':
			self.cpu.write_reg(a, self.cpu.pop_stack()) if a in 'abcd' else self.cpu.pop_stack()
		elif cmd == 'push':
			self.cpu.write_stack(v)
		elif cmd in ['pushr', 'pushrr']:
			for r in 'abcd' if cmd == 'pushr' else 'dcba':
				self.cpu.write_stack(self.cpu.read_reg(r))
		elif cmd in ['popr', 'poprr']:
			for r in 'abcd' if cmd == 'poprr' else 'dcba':
				self.cpu.write_reg(r, self.cpu.pop_stack())
		else:
			r = self.cpu.pop_stack() if cmd[-1] != 'a' else self.cpu.read_reg('a')
			for _ in range(v - 1):
				r = OP[cmd if cmd[-1] != 'a' else cmd[:-1]](r, self.cpu.pop_stack())
			self.cpu.write_reg(b if b in 'abcd' else 'a', r)


from functools import reduce
arop = {'add': lambda a, b: a + b, 'sub': lambda a, b: a - b, 'mul': lambda a, b: a * b, 'div': lambda a, b: a // b, 'and': lambda a, b: a & b, 'or': lambda a, b: a | b, 'xor': lambda a, b: a ^ b}

class Machine(object):

	def __init__(self, cpu):
		self.cpu = cpu

	def rv(self, x):
		try:
			return int(x)
		except ValueError:
			return self.cpu.read_reg(x)

	def execute(self, instr):
		(op, a, b) = (instr.split(' ') + [None, None, None])[:3]
		if a:
			a = a.rstrip(',')
		if op in ('pushrr', 'poprr'):
			regs = 'dcba'
			op = op[:-1]
		else:
			regs = 'abcd'
		if op[-1:] == 'a':
			self.cpu.write_stack(self.cpu.read_reg('a'))
			op = op[:-1]
		if op == 'push':
			self.cpu.write_stack(self.rv(a))
		elif op in arop:
			self.cpu.write_reg(b if b else 'a', reduce(arop[op], (self.cpu.pop_stack() for _ in range(self.rv(a)))))
		elif op == 'mov':
			self.cpu.write_reg(b, self.rv(a))
		elif op == 'pop':
			if a:
				self.cpu.write_reg(a, self.cpu.pop_stack())
			else:
				self.cpu.pop_stack()
		elif op == 'pushr':
			for r in regs:
				self.cpu.write_stack(self.cpu.read_reg(r))
		elif op == 'popr':
			for r in regs[::-1]:
				self.cpu.write_reg(r, self.cpu.pop_stack())


import re
from operator import add, sub, mul, floordiv, and_, or_, xor

class Machine(object):

	def __init__(self, cpu):
		self.cpu = cpu

	def reg_or_int(self, val):
		if val in 'abcd':
			return self.cpu.read_reg(val)
		return int(val)

	def stack_op(self, instr):
		match = re.fullmatch('push ([a-d]|\\d+)', instr)
		if match:
			self.cpu.write_stack(self.reg_or_int(match.group(1)))
			return
		match = re.fullmatch('pop( ([a-d]))?', instr)
		if match:
			val = self.cpu.pop_stack()
			if match.group(2):
				self.cpu.write_reg(match.group(2), val)
			return
		match = re.fullmatch('(push|pop)r(r)?', instr)
		if match:
			if match.group(1) == 'push':
				for reg in 'dcba' if match.group(2) else 'abcd':
					self.cpu.write_stack(self.cpu.read_reg(reg))
			else:
				for reg in 'abcd' if match.group(2) else 'dcba':
					self.cpu.write_reg(reg, self.cpu.pop_stack())
			return
		raise ValueError('Invalid instruction')

	def move_op(self, instr):
		match = re.fullmatch('mov ([a-d]|\\d+), ([a-d])', instr)
		if match:
			self.cpu.write_reg(match.group(2), self.reg_or_int(match.group(1)))
			return
		raise ValueError('Invalid instruction')

	def arith_op(self, instr):
		match = re.fullmatch('(add|sub|mul|div|and|or|xor)(a)? ([a-d]|\\d+)(, ([a-d]))?', instr)
		if match:
			op = {'add': add, 'sub': sub, 'mul': mul, 'div': floordiv, 'and': and_, 'or': or_, 'xor': xor}[match.group(1)]
			if match.group(2):
				self.cpu.write_stack(self.cpu.read_reg('a'))
			operand_size = self.reg_or_int(match.group(3))
			save_reg = match.group(5) or 'a'
			val = self.cpu.pop_stack()
			for _ in range(1, operand_size):
				val = op(val, self.cpu.pop_stack())
			self.cpu.write_reg(save_reg, val)
			return
		raise ValueError('Invalid instruction')

	def execute(self, instr):
		if instr.startswith('p'):
			self.stack_op(instr)
		elif instr.startswith('mov'):
			self.move_op(instr)
		else:
			self.arith_op(instr)


from operator import add, sub, mul, floordiv, or_, xor, and_
import re

class Machine(object):
	OP_FUNCS = {'add': add, 'sub': sub, 'mul': mul, 'div': floordiv, 'or': or_, 'xor': xor, 'and': and_}
	(REG_LST, REG_REVLST) = ('abcd', 'dcba')
	REG_SET = set(REG_LST)

	def __init__(self, cpu):
		self.cpu = cpu

	def execute(self, instr):
		cmds = re.split('[ ,]+', instr)
		if cmds[0] == 'pop':
			self.cpu.pop_stack() if len(cmds) == 1 else self.pop(cmds[1])
		elif cmds[0] == 'popr':
			self.loop(self.REG_REVLST, self.pop)
		elif cmds[0] == 'poprr':
			self.loop(self.REG_LST, self.pop)
		elif cmds[0] == 'push':
			self.push(cmds[1])
		elif cmds[0] == 'pushr':
			self.loop(self.REG_LST, self.push)
		elif cmds[0] == 'pushrr':
			self.loop(self.REG_REVLST, self.push)
		elif cmds[0] == 'mov':
			self.mov(cmds[1], 'a' if len(cmds) == 2 else cmds[2])
		else:
			self.operation(cmds[0], cmds[1], 'a' if len(cmds) == 2 else cmds[2])

	def push(self, regint):
		self.cpu.write_stack(self.cpu.read_reg(regint) if regint in 'abcd' else int(regint))

	def pop(self, reg):
		self.cpu.write_reg(reg, self.cpu.pop_stack())

	def mov(self, val, reg):
		self.cpu.write_reg(reg, int(val))

	def loop(self, regLst, func):
		for reg in regLst:
			func(reg)

	def operation(self, opType, regint, reg):
		nToPop = self.cpu.read_reg(regint) if regint in 'abcd' else int(regint)
		if opType[-1] == 'a':
			opType = opType[:-1]
			self.push('a')
		result = self.cpu.pop_stack()
		for x in range(nToPop - 1):
			result = self.OP_FUNCS[opType](result, self.cpu.pop_stack())
		self.cpu.write_reg(reg, result)


from functools import partial, reduce
from operator import add, sub, mul, floordiv, and_, or_, xor
OPERATIONS = {'add': add, 'sub': sub, 'mul': mul, 'div': floordiv, 'and': and_, 'or': or_, 'xor': xor}

class Machine(object):

	def __init__(self, cpu):
		self.cpu = cpu

	def read(self, reg):
		return self.cpu.readReg(reg)

	def mov(self, value, reg):
		self.cpu.writeReg(reg, int(value))

	def push(self, value):
		self.cpu.writeStack(int(value))

	def pop(self, reg=None):
		value = self.cpu.popStack()
		if reg:
			self.mov(value, reg)
		return value

	def pushr(self):
		for reg in 'abcd':
			self.push(self.read(reg))

	def pushrr(self):
		for reg in 'dcba':
			self.push(self.read(reg))

	def popr(self):
		for reg in 'dcba':
			self.pop(reg)

	def poprr(self):
		for reg in 'abcd':
			self.pop(reg)

	def _op_(self, op, n, reg='a'):
		values = (self.pop() for _ in range(n))
		self.mov(reduce(op, values), reg)

	def _opx_(self, op, src, n, reg='a'):
		self.push(self.read(src))
		self._op_(op, n, reg)

	def get(self, value):
		return int(value) if value.isdigit() else self.read(value)

	def execute(self, instr):
		(cmd, _, args) = instr.partition(' ')
		args = args.split(', ') if args else []
		if args and cmd != 'pop':
			args[0] = self.get(args[0])
		if cmd in OPERATIONS:
			self._op_(OPERATIONS[cmd], *args)
		elif cmd[:-1] in OPERATIONS:
			self._opx_(OPERATIONS[cmd[:-1]], cmd[-1], *args)
		else:
			getattr(self, cmd)(*args)


import operator
from functools import partialmethod, reduce

class Machine(object):

	def __init__(self, cpu):
		cpu.read_reg = cpu.readReg
		cpu.write_reg = cpu.writeReg
		cpu.pop_stack = cpu.popStack
		cpu.push_stack = cpu.writeStack
		self.cpu = cpu

	def execute(self, instruction):
		instr = instruction.replace(',', '').split()
		(op, args) = (instr[0], instr[1:])
		op = '_{}'.format(op)
		getattr(self, op)(*args)

	def _push(self, values=None):
		for x in ensure_list(values):
			self.cpu.push_stack(self.value(x))

	def _pop(self, registers=None):
		for reg in ensure_list(registers):
			y = self.cpu.pop_stack()
			if reg:
				self.cpu.write_reg(reg, y)
	_pushr = partialmethod(_push, values=list('abcd'))
	_pushrr = partialmethod(_push, values=list('dcba'))
	_popr = partialmethod(_pop, registers=list('dcba'))
	_poprr = partialmethod(_pop, registers=list('abcd'))

	def _mov(self, a=None, b=None):
		self.cpu.write_reg(b, int(a))

	def value(self, var):
		try:
			return int(var)
		except ValueError:
			return self.cpu.read_reg(var)

def ensure_list(a):
	if not isinstance(a, list):
		a = [a]
	return a

def build_arithmetic_op(func):

	def f(machine, n=None, register='a'):
		result = func((machine.cpu.pop_stack() for x in range(machine.value(n))))
		machine.cpu.write_reg(register, int(result))
	return f

def push_a_then(func):

	def f(machine, *args, **kwargs):
		x = machine.cpu.read_reg('a')
		machine.cpu.push_stack(x)
		func(machine, *args, **kwargs)
	return f
_arithmetic = {'_add': sum, '_sub': lambda i: reduce(operator.sub, i), '_mul': lambda i: reduce(operator.mul, i), '_div': lambda i: reduce(operator.truediv, i), '_and': lambda i: reduce(operator.and_, i), '_or': lambda i: reduce(operator.or_, i), '_xor': lambda i: reduce(operator.xor, i)}
for (name, func) in list(_arithmetic.items()):
	method = build_arithmetic_op(func)
	setattr(Machine, name, method)
	setattr(Machine, name + 'a', push_a_then(method))


from functools import reduce

class Machine(object):

	def __init__(self, cpu):
		self.cpu = cpu

	def execute(self, instr):
		i = instr
		if i[0] == 'p':

			def doa(a):
				for (k, l) in a:
					self.cpu.write_stack(l)

			def dob(a):
				for k in a:
					self.cpu.write_reg(k, self.cpu.pop_stack())
			inst = i.split()
			if inst[0] == 'push':
				self.cpu.write_stack(self.cpu.read_reg(inst[1]) if inst[1].isalpha() else int(inst[1]))
			elif inst[0] == 'pop':
				if len(inst) == 1:
					self.cpu.pop_stack()
				else:
					self.cpu.write_reg(inst[1], self.cpu.pop_stack())
			elif inst[0] == 'pushr':
				doa(self.cpu.registers.items())
			elif inst[0] == 'pushrr':
				doa(reversed(list(self.cpu.registers.items())))
			elif inst[0] == 'popr':
				dob(['d', 'c', 'b', 'a'])
			elif inst[0] == 'poprr':
				dob(['a', 'b', 'c', 'd'])
		elif i.startswith('mov'):
			inst = i.replace(',', '').split()
			self.cpu.write_reg(inst[2], self.cpu.read_reg(inst[1]) if inst[1].isalpha() else int(inst[1]))
		else:

			def do(inst, op, a, b, l):
				(reg, val) = ('a' if l == 2 else inst[2], self.cpu.read_reg(inst[1]) if inst[1].isalpha() else int(inst[1]))
				s = self.cpu.read_reg('a') if inst[0][-1] == 'a' else self.cpu.pop_stack() if a else 0 if op == '+' else 1
				s = reduce(lambda x, y: eval('x {} y'.format(op)), [s] + [self.cpu.stack.pop() for _ in range(val - b)])
				self.cpu.write_reg(reg, s)
			inst = i.replace(',', '').split()
			l = len(inst)
			if inst[0].startswith('add'):
				do(inst, '+', 0, inst[0][-1] == 'a', l)
			elif inst[0].startswith('sub'):
				do(inst, '-', 1, 1, l)
			elif inst[0].startswith('mul'):
				do(inst, '*', 0, inst[0][-1] == 'a', l)
			elif inst[0].startswith('div'):
				do(inst, '//', 1, 1, l)
			elif inst[0].startswith('and'):
				do(inst, '&', 1, 1, l)
			elif inst[0].startswith('or'):
				do(inst, '|', 0, inst[0][-1] == 'a', l)
			elif inst[0].startswith('xor'):
				do(inst, '^', 0, inst[0][-1] == 'a', l)


import operator

class Machine(object):

	def __init__(self, cpu):
		self.cpu = cpu
		self.registers = ['a', 'b', 'c', 'd']
		self.operations = {'add': operator.add, 'adda': operator.add, 'sub': operator.sub, 'suba': operator.sub, 'mul': operator.mul, 'mula': operator.mul, 'div': operator.truediv, 'diva': operator.truediv, 'and': operator.and_, 'anda': operator.and_, 'or': operator.or_, 'ora': operator.or_, 'xor': operator.xor, 'xora': operator.xor}

	def execute(self, instr):
		instr_list = instr.split()
		command = instr_list[0]
		if command == 'push':
			val = int(instr_list[1]) if instr_list[1].isdigit() else self.cpu.read_reg(instr_list[1])
			self.cpu.write_stack(val)
		elif command == 'pop':
			val = self.cpu.pop_stack()
			if len(instr_list) == 2:
				reg_name = instr_list[1]
				self.cpu.write_reg(reg_name, val)
		elif command == 'pushr':
			for reg in self.registers:
				val = self.cpu.read_reg(reg)
				self.cpu.write_stack(val)
		elif command == 'pushrr':
			for reg in self.registers[::-1]:
				val = self.cpu.read_reg(reg)
				self.cpu.write_stack(val)
		elif command == 'popr':
			for reg in self.registers[::-1]:
				val = self.cpu.pop_stack()
				self.cpu.write_reg(reg, val)
		elif command == 'poprr':
			for reg in self.registers:
				val = self.cpu.pop_stack()
				self.cpu.write_reg(reg, val)
		elif command == 'mov':
			first_el = instr_list[1][:-1]
			if first_el.isdigit():
				self.cpu.write_reg(instr_list[2], int(first_el))
			else:
				val = self.cpu.read_reg(first_el)
				self.cpu.write_reg(instr_list[2], val)
		else:
			if instr_list[1][-1] == ',':
				first_el = instr_list[1][:-1]
				destination_reg = instr_list[2]
			else:
				first_el = instr_list[1]
				destination_reg = 'a'
			if command[-1] == 'a':
				self.cpu.write_stack(self.cpu.read_reg('a'))
			start_op = self.cpu.pop_stack()
			how_many = int(first_el) if first_el.isdigit() else self.cpu.read_reg(first_el)
			for i in range(how_many - 1):
				start_op = self.operations[command](start_op, self.cpu.pop_stack())
			self.cpu.write_reg(destination_reg, int(start_op))


from operator import add, sub, mul, floordiv, and_, or_, xor
from functools import reduce

class Machine(object):

	def __init__(self, cpu):
		self.cpu = cpu

	def execute(self, ins):
		(left, right) = ('abcd', 'dcba')
		cpu = self.cpu
		value_of = lambda x: cpu.read_reg(x) if x in left else int(x)
		(i, *a) = ins.replace(',', '').split()
		if i.endswith('a'):
			cpu.write_stack(cpu.read_reg('a'))
			i = i[:-1]
		seq = lambda f: cpu.write_reg(a[1] if len(a) > 1 else 'a', reduce(f, [cpu.pop_stack() for _ in range(value_of(a[0]))]))
		if i == 'push':
			cpu.write_stack(value_of(a[0]))
		elif i == 'pop':
			e = cpu.pop_stack()
			if len(a):
				cpu.write_reg(a[0], e)
		elif i == 'pushr':
			for c in left:
				self.execute('push ' + c)
		elif i == 'pushrr':
			for c in right:
				self.execute('push ' + c)
		elif i == 'popr':
			for c in right:
				self.execute('pop ' + c)
		elif i == 'poprr':
			for c in left:
				self.execute('pop ' + c)
		elif i == 'mov':
			cpu.write_reg(a[1], value_of(a[0]))
		elif i == 'add':
			seq(add)
		elif i == 'sub':
			seq(sub)
		elif i == 'mul':
			seq(mul)
		elif i == 'div':
			seq(floordiv)
		elif i == 'and':
			seq(and_)
		elif i == 'or':
			seq(or_)
		elif i == 'xor':
			seq(xor)


class Machine(object):

	def __init__(self, cpu: CPU):
		self.cpu = cpu

	def execute(self, instr: str):
		ins_lst = instr.split(' ')
		if ins_lst[0] == 'push':
			if ins_lst[1].isdigit():
				self.cpu.write_stack(int(ins_lst[1]))
			else:
				self.cpu.write_stack(self.cpu.read_reg(ins_lst[1]))
		elif ins_lst[0] == 'pop':
			value = self.cpu.pop_stack()
			if len(ins_lst) > 1:
				self.cpu.write_reg(ins_lst[1], value)
		elif ins_lst[0] == 'pushr':
			for reg in ['a', 'b', 'c', 'd']:
				self.cpu.write_stack(self.cpu.read_reg(reg))
		elif ins_lst[0] == 'pushrr':
			for reg in ['d', 'c', 'b', 'a']:
				self.cpu.write_stack(self.cpu.read_reg(reg))
		elif ins_lst[0] == 'popr':
			for reg in ['d', 'c', 'b', 'a']:
				self.cpu.write_reg(reg, self.cpu.pop_stack())
		elif ins_lst[0] == 'poprr':
			for reg in ['a', 'b', 'c', 'd']:
				self.cpu.write_reg(reg, self.cpu.pop_stack())
		elif ins_lst[0] == 'mov':
			ins_lst[1] = ins_lst[1][:-1]
			value = 0
			if ins_lst[1].isdigit():
				value = int(ins_lst[1])
			else:
				value = self.cpu.read_reg(ins_lst[1])
			self.cpu.write_reg(ins_lst[2], value)
		else:
			if len(ins_lst[0]) == 4 or (len(ins_lst[0]) == 3 and ins_lst[0][:2] == 'or'):
				self.cpu.write_stack(self.cpu.read_reg(ins_lst[0][-1]))
				ins_lst[0] = ins_lst[0][:-1]
			(num, target_reg) = (0, 'a')
			if ins_lst[1][-1] == ',':
				ins_lst[1] = ins_lst[1][:-1]
			if ins_lst[1].isdigit():
				num = int(ins_lst[1])
			else:
				num = self.cpu.read_reg(ins_lst[1])
			if len(ins_lst) > 2:
				target_reg = ins_lst[2]
			exe_func = lambda x, y: x
			if ins_lst[0] == 'add':
				exe_func = lambda x, y: x + y
			elif ins_lst[0] == 'sub':
				exe_func = lambda x, y: x - y
			elif ins_lst[0] == 'mul':
				exe_func = lambda x, y: x * y
			elif ins_lst[0] == 'div':
				exe_func = lambda x, y: x // y
			elif ins_lst[0] == 'and':
				exe_func = lambda x, y: x & y
			elif ins_lst[0] == 'or':
				exe_func = lambda x, y: x | y
			elif ins_lst[0] == 'xor':
				exe_func = lambda x, y: x ^ y
			result = self.cpu.pop_stack()
			for _ in range(num - 1):
				result = exe_func(result, self.cpu.pop_stack())
			self.cpu.write_reg(target_reg, result)