Skip to content

Instantly share code, notes, and snippets.

@DeclanHoare
Last active August 25, 2017 12:23
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 DeclanHoare/8a72dc4678d1ccdb9795a4d24edf23d5 to your computer and use it in GitHub Desktop.
Save DeclanHoare/8a72dc4678d1ccdb9795a4d24edf23d5 to your computer and use it in GitHub Desktop.
fractran interpreter in python
import sys
if len(sys.argv) != 3:
sys.stderr.write("usage: " + sys.argv[0] + " PROGRAM INPUT\n")
sys.exit(1)
inp = int(sys.argv[2])
sys.stdout.write(str(inp) + " ")
symbols = []
currnum = ""
with open(sys.argv[1], "r") as fobj:
while True:
byte = fobj.read(1)
if byte.isdigit():
currnum += byte
elif byte == "/" or byte.isspace() or byte == "":
if currnum:
symbols.append(int(currnum))
currnum = ""
if byte == "/":
symbols.append("/")
elif byte == "":
break
program = []
num = None
div = False
for symbol in symbols:
if isinstance(symbol, int):
if div:
if num == None:
sys.stderr.write("unexpected /\n")
sys.exit(1)
program.append((num, symbol))
num = None
div = False
else:
if num != None:
program.append((num, 1))
num = symbol
elif symbol == "/":
div = True
if num != None:
program.append((num, 1))
cont = True
while cont:
cont = False
for i in program:
if isinstance(i, tuple):
(numerator, denominator) = i
nf = numerator * inp
if nf % denominator == 0:
inp = nf / denominator
sys.stdout.write(str(inp) + " ")
cont = True
break
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment