Skip to content

Instantly share code, notes, and snippets.

@riceissa
Created July 15, 2020 07:15
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 riceissa/5b20b966c22e181290a8d8eec5f481cd to your computer and use it in GitHub Desktop.
Save riceissa/5b20b966c22e181290a8d8eec5f481cd to your computer and use it in GitHub Desktop.
For Exercise 3.2 in Sipser's book
10#10___
1
x0#10___
3
x0#10___
3
x0#10___
5
x0#x0___
6
x0#x0___
7
x0#x0___
7
x0#x0___
1
xx#x0___
2
xx#x0___
4
xx#x0___
4
xx#xx___
6
xx#xx___
6
xx#xx___
7
xx#xx___
1
xx#xx___
8
xx#xx___
8
xx#xx___
8
xx#xx___
a
#!/usr/bin/env python3
# This is the Turing machine M_1 from Sipser's Introduction to the Theory of
# Computation (3rd ed), Example 3.9 on page 173.
def state_repr(state):
if isinstance(state, int):
return str(state)
if state == "accept":
return "a"
return "r"
def print_configuration(tape, state, loc):
print("".join(tape))
print((" " * loc) + state_repr(state))
tape = [c for c in "10#10___"]
state = 1
loc = 0
while state not in ["accept", "reject"]:
print_configuration(tape, state, loc)
if state == 1:
if tape[loc] == "0":
tape[loc] = "x"
loc += 1
state = 2
elif tape[loc] == "1":
tape[loc] = "x"
loc += 1
state = 3
elif tape[loc] == "#":
loc += 1
state = 8
else:
state = "reject"
elif state == 2:
if tape[loc] in ["0", "1"]:
loc += 1
elif tape[loc] == "#":
loc += 1
state = 4
else:
state = "reject"
elif state == 3:
if tape[loc] in ["0", "1"]:
loc += 1
elif tape[loc] == "#":
loc += 1
state = 5
else:
state = "reject"
elif state == 4:
if tape[loc] == "x":
loc += 1
elif tape[loc] == "0":
tape[loc] = "x"
loc -= 1
state = 6
else:
state = "reject"
elif state == 5:
if tape[loc] == "x":
loc += 1
elif tape[loc] == "1":
tape[loc] = "x"
loc -= 1
state = 6
else:
state = "reject"
elif state == 6:
if tape[loc] in ["0", "1", "x"]:
loc -= 1
elif tape[loc] == "#":
loc -= 1
state = 7
else:
state = "reject"
elif state == 7:
if tape[loc] in ["0", "1"]:
loc -= 1
elif tape[loc] == "x":
loc += 1
state = 1
else:
state = "reject"
elif state == 8:
if tape[loc] == "x":
loc += 1
elif tape[loc] == "_":
loc += 1
state = "accept"
else:
state = "reject"
print_configuration(tape, state, loc)
@riceissa
Copy link
Author

equation006

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment