Skip to content

Instantly share code, notes, and snippets.

@fayimora
Last active August 29, 2015 13:56
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 fayimora/8817259 to your computer and use it in GitHub Desktop.
Save fayimora/8817259 to your computer and use it in GitHub Desktop.
Turing Machine/Program Simulation for ECS631 Assignment
import sys, argparse
args, res = None, None
def info(tape, n, config):
"""Do shananigans before any computation"""
if(args.verbose):
print("Config: %s" % config)
print("Cursor is at %d" % n)
print("Tape is ")
if(args.strings):
res = ''.join(map(lambda i: str(i), tape))
print(res)
else:
res = tape
print(res)
print("=" * len(tape))
def f(tape, n):
info(tape, n, "f")
pos = n
if(tape[pos] == '0' or tape[pos] == '1'):
pos += 2 # move to the right twice
f(tape, pos)
elif(tape[pos] == ''):
tape[pos] = '0'
pos -= 2 # move to the left twice
c(tape, pos)
def p(tape, n):
info(tape, n, "p")
pos = n
if(tape[pos] == 'x'):
tape[pos] = ''
pos += 1 # move to the right once
q(tape, pos)
elif(tape[pos] == 'e'):
pos += 1 # move to the right once
f(tape, pos)
elif(tape[pos] == ''):
pos -= 2 # move to the left twice
p(tape, pos)
def q(tape, n):
info(tape, n, "q")
pos = n
if(tape[pos] == '0' or tape[pos] == '1'):
pos += 2 # move to the right twice
q(tape, pos)
elif(tape[pos] == ''):
tape[pos] = '1'
pos -= 1 # move to the left once
p(tape, pos)
def c(tape, n):
info(tape, n, "c")
pos = n
if(tape[pos] == '1'):
pos += 1 # move to the right once
tape[pos] = 'x'
pos -= 3 # move to the left 3 times
c(tape, pos)
elif(tape[pos] == '0'):
q(tape, pos)
def b(tape, n):
info(tape, n, "b")
pos = n
if tape[pos] == 'e':
tape[pos] = 'e'
pos += 1 # move to the right once
tape[pos] = '0'
pos += 2 # move to the right twice
tape[pos] = '0'
pos -= 2
c(tape, pos)
def main(args):
tape, n = ['e'], 0
for i in range(0, args.tape_length): tape.append('')
try:
b(tape, n)
except IndexError:
print("Stopped for now")
if __name__ == '__main__':
parser = argparse.ArgumentParser("A simulation of a turing program computinga sequence")
parser.add_argument('tape_length', type=int, help='The length of the tape')
parser.add_argument('-s', '--strings', action='store_true', default=False, help='print strings rather than arrays')
parser.add_argument('-v', '--verbose', action='store_true', default=False, help='Verbose mode. Print all helpful messages')
args = parser.parse_args()
main(args)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment