diff TM.py @ 45:1804f09a7adb

Chapter 6, exercise 4, part 4. A Turing Machine drawer.
author Brian Neal <bgneal@gmail.com>
date Sat, 19 Jan 2013 14:17:12 -0600
parents 362d4ec7e794
children
line wrap: on
line diff
--- a/TM.py	Wed Jan 16 21:44:02 2013 -0600
+++ b/TM.py	Sat Jan 19 14:17:12 2013 -0600
@@ -79,6 +79,9 @@
         self.actions = actions      # action table
         self.state = init_state     # state
 
+        # keep a history of head position & state tuples
+        self.history = []
+
     def loop(self, steps=1):
         """Attempts to execute the given number of steps. May exit early if the
         machine is already halted or halts during execution.
@@ -97,6 +100,11 @@
 
     def step(self):
         """Executes one time step by computing the next row of the array."""
+
+        if len(self.history) == 0:
+            # record initial head position & state
+            self.history.append((self.head, self.state))
+
         i = self.next - 1   # the previous state of the tape
         j = self.next       # the row to write
         self.next += 1
@@ -129,6 +137,9 @@
         # change state
         self.state = next_state
 
+        # record what happened in our history
+        self.history.append((self.head, self.state))
+
     def get_array(self, start=0, end=None):
         """Gets a slice of columns from the array, with slice indices
         (start, end).  Avoid copying if possible.
@@ -160,3 +171,17 @@
     count = tm.loop(n - 1)
     print count
     print tm.array
+
+    from TMDrawer import TMDrawer
+
+    tape_colors = {0: 0, 1: 40}
+    state_colors = {
+        A: 10,
+        B: 20,
+        C: 30,
+        None: 40
+    }
+
+    drawer = TMDrawer(tape_colors, state_colors, cmap='spectral')
+    drawer.draw(tm)
+    drawer.show()