Skip to content

Instantly share code, notes, and snippets.

@Sasszem
Created April 14, 2020 19:20
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 Sasszem/1f7b1b1fc342d0deffd7d151c21fd1c5 to your computer and use it in GitHub Desktop.
Save Sasszem/1f7b1b1fc342d0deffd7d151c21fd1c5 to your computer and use it in GitHub Desktop.
The simplest possible way of printing the first 100 fibonacci numbers in python
from collections import namedtuple, deque
from sys import stdin, stdout
class SVM:
def __init__(self, progmem = "H", stack = [], status = [0, False]):
self.progmem = progmem
self.stack = deque(stack)
self.PC, self.HALT = status
def step(self):
if self.HALT:
return
#print(self.stack)
#print(self.PC)
instr = self.progmem[self.PC]
#print(instr)
self.PC += 1
if instr=="H":
self.HALT = True
elif instr=="D":
self.stack.append(self.stack[-1])
elif instr=="S":
a = self.stack.pop()
b = self.stack.pop()
self.stack.append(a)
self.stack.append(b)
elif instr=="R":
a = self.stack.pop()
b = self.stack.pop()
c = self.stack.pop()
self.stack.append(b)
self.stack.append(a)
self.stack.append(c)
elif instr=="+":
self.stack.append(self.stack.pop() + self.stack.pop())
elif instr=="-":
self.stack.append(-self.stack.pop())
elif instr=="*":
self.stack.append(self.stack.pop() * self.stack.pop())
elif instr=="I":
self.stack.append(int(input()))
elif instr=="i":
self.stack.append(stdin.read(1))
elif instr=="O":
stdout.write(str(self.stack.pop()))
elif instr=="o":
stdout.write(chr(self.stack.pop()))
elif instr=="d":
self.stack.pop()
elif instr in ("0", "1", "2"):
self.PC -= 1
n = 0
while self.progmem[self.PC] in ("0", "1", "2"):
n *= 3
n += int(self.progmem[self.PC])
self.PC += 1
self.stack.append(n)
elif instr=="B":
if self.stack.pop()==0:
self.PC = self.stack.pop()
elif instr=="J":
self.PC = self.stack.pop()
elif instr=="#":
pass
else:
raise Exception(f"Supplied memory wrong af!")
#todo: swap stack & progmem instead
v = SVM("1O101o10200#0#1DR+DO101oR1-+D01121SBdRR120JH")
while not v.HALT:
v.step()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment