Skip to content

Instantly share code, notes, and snippets.

@carlos-aguayo
Created January 17, 2015 23:49
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 carlos-aguayo/5bd33f0c5007acb0de7f to your computer and use it in GitHub Desktop.
Save carlos-aguayo/5bd33f0c5007acb0de7f to your computer and use it in GitHub Desktop.
Turing machine, single head, single tape
######################################################################
# Task: Describe a Turing machine that shifts the input string one
# space to the right and places the symbol ($) in the first location
# on the tape.
######################################################################
# Enter values below for
# q_0 : the initial state (an int)
# q_a : the accept state (an int)
# q_r : the reject state (an int)
# delta : the transition function expressed as a dictionary
# with keys (state, symbol) and values (state, symbol, 'L' or 'R')
# Use the 'b' character for the blank symbol.
#
# For example, you might express the TM that appends a 1 as follows:
#
# q_0 = 0
# q_a = 1
# q_r = 2
# delta = {}
# delta[(0,'0')] = (0,'0','R')
# delta[(0,'1')] = (0,'1','R')
# delta[(0,'b')] = (1,'1','R')
######################################################################
test_tape = ['0','1', '0', '1']
#Specify your turing machine here
q_0 = 0
q_a = 6
q_r = 7
delta = {}
delta[(0,'0')] = (0,'0','R')
delta[(0,'1')] = (0,'1','R')
delta[(0,'b')] = (1,'b','L')
delta[(1,'0')] = (2,'b','R')
delta[(1,'1')] = (4,'b','R')
delta[(1,'b')] = (6,'$','R')
delta[(2,'0')] = (3,'0','L')
delta[(2,'1')] = (3,'0','L')
delta[(2,'b')] = (3,'0','L')
delta[(3,'0')] = (1,'0','L')
delta[(3,'1')] = (1,'1','L')
delta[(3,'b')] = (1,'b','L')
delta[(4,'0')] = (5,'1','L')
delta[(4,'1')] = (5,'1','L')
delta[(4,'b')] = (5,'1','L')
delta[(5,'0')] = (1,'0','L')
delta[(5,'1')] = (1,'1','L')
delta[(5,'b')] = (1,'b','L')
######
currentState = q_0
head = 0
test_tape.append('b')
while True:
# print "currentState: " + str(currentState)
# print "head: " + str(head)
print "".join(test_tape[0:head]) + "(q_" + str(currentState) + ")" + "".join(test_tape[head:])
currentState, write, move = delta[(currentState, test_tape[head])]
test_tape[head] = write
if move == 'L':
head -= 1
else:
head += 1
if head < 0:
head = 0
if currentState == q_a:
print "accept"
break;
if currentState == q_r:
print "reject"
break;
#print "".join(test_tape[0:head]) + "|q_" + str(currentState) + "|" + "".join(test_tape[head:])
print test_tape
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment