Reversable/Python Implementation

From Esolang
Jump to navigation Jump to search

Original (and ugly) python implementation of Reversable, by User:Dulph

class ReversableError(Exception):
    pass

prog=input()
direction=1
c=0
prog=prog.split(" ")
variables={}
while c < len(prog) and c >= 0:
    if prog[c]=="SKIP":
        c+=direction
    elif prog[c]=="REVERSE":
        direction=-direction
    elif "REVERSE" in prog[c]:
        t=prog[c].split("<")
        if t[1]:
            direction=-direction
    elif "GET" in prog[c]:
        t=prog[c].split("-")
        if t[1][0] not in ["I", "S"]:
            raise ReversableError("%s is not a valid variable type"%t[1][0])
        elif t[1][0] == "I":
            variables[t[1]]=int(input()[0])
        else:
            variables[t[1]]=input()[0]
    elif "OUT" in prog[c]:
        t=prog[c].split("-")
        print(variables[t[1]])
    elif "+" in prog[c]:
        t=prog[c].split("+")
        try:
            variables[t[0]]
        except KeyError:
            variables[t[0]]=0
        try:
            variables[t[1]]
        except KeyError:
            variables[t[1]]=0
        variables[t[0]] += variables[t[1]]
    elif "-" in prog[c]:
        t=prog[c].split("-")
        try:
            variables[t[0]]
        except KeyError:
            variables[t[0]]=0
        try:
            variables[t[1]]
        except KeyError:
            variables[t[1]]=0
        variables[t[0]] -= variables[t[1]]
    elif "*" in prog[c]:
        t=prog[c].split("*")
        try:
            variables[t[0]]
        except KeyError:
            variables[t[0]]=0
        try:
            variables[t[1]]
        except KeyError:
            variables[t[1]]=0
        variables[t[0]] *= variables[t[1]]
    elif "%" in prog[c]:
        t=prog[c].split("%")
        try:
            variables[t[0]]
        except KeyError:
            variables[t[0]]=0
        try:
            variables[t[1]]
        except KeyError:
            variables[t[1]]=0
        variables[t[0]] %= variables[t[1]]
    elif prog[c] != "NOP":
        print("Unknown command :", prog[c])
    c+=direction