Turing Machine Code
unknown
python
2 years ago
2.4 kB
7
Indexable
from instream import InStream import tape class TouringMachine: def __init__(self,file): file_in = InStream(file) self.n = file_in.readInt() self.alphabet = file_in.readString() self.action = [0]*self.n self.next = {} self.out = {} for i in range(self.n): self.action[i] = file_in.readString() if self.action[i] == "Halt": continue if self.action[i] == "Yes": continue if self.action[i] == "No": continue self.next[i] = {} for j in range(len(self.alphabet)): state = int(file_in.readInt()) self.next[i][self.alphabet[j]] = state self.out[i] = {} for j in range(len(self.alphabet)): symbol = file_in.readString()[0] self.out[i][self.alphabet[j]] = symbol def simulate(self,string): Tape = tape.Tape(string) state = 0 while(self.action[state] == "L") or (self.action[state] == "R"): if (self.action[state] == "R"): Tape.moveRight() if (self.action[state] == "L"): Tape.moveLeft() c = Tape.read() Tape.write(self.out[state][c]) state = self.next[state][c] return self.action[state] + " " + str(Tape) string = "1010+11" newTM = TouringMachine("test.txt") print(newTM.simulate(string)) ``` #The Mechanism to read over the input string is this one: ```py from collections import deque class Tape: def __init__(self,string): self.left = deque() self.right = deque() self.current = None self.right.append("#") for i in range(len(string)): self.right.append(string[i]) self.current = self.right.pop() def read(self): return self.current def write(self,symbol): self.current = symbol def moveLeft(self): self.right.append(self.current) if len(self.left) == 0: self.left.append("#") self.current = self.left.pop() def moveRight(self): self.left.append(self.current) if len(self.right) == 0: self.right.append("#") self.current = self.right.pop() def __str__(self): test = "" while len(self.left) != 0: x = self.left.popleft() if x != "#": test += test.join(x) return test
Editor is loading...