class States: UNDEFINED = "UNDEFINED" STOP = "STOP" ACCEPT = "ACCEPT" S = "S" SC1 = "SC1" SC2 = "SC2" # TM akceptująca ciąg gdy po raz trzeci odczyta symbol c (zbiór dopuszczalnych symboli to {a, b, c}). tansitionTable = [ {"in": {"currentState": States.S, "currentSymbol": "c"}, "out": {"newState": States.SC1, "newSymbol": "C", "headMove": "R"}}, {"in": {"currentState": States.SC1, "currentSymbol": "c"}, "out": {"newState": States.SC2, "newSymbol": "C", "headMove": "R"}}, {"in": {"currentState": States.SC2, "currentSymbol": "c"}, "out": {"newState": States.ACCEPT, "newSymbol": "C", "headMove": "-"}}, {"in": {"currentState": States.S, "currentSymbol": None}, "out": {"newState": States.S, "newSymbol": "-", "headMove": "R"}}, {"in": {"currentState": States.SC1, "currentSymbol": None}, "out": {"newState": States.SC1, "newSymbol": "-", "headMove": "R"}}, {"in": {"currentState": States.SC2, "currentSymbol": None}, "out": {"newState": States.SC2, "newSymbol": "-", "headMove": "R"}} ] class TM: tansitionTable = None currentState = None stopState = None tape = None headPosition = None def __init__(self, *, initState, stopState, tansitionTable, tape, headPosition): self.currentState = initState self.stopState = stopState self.tansitionTable = tansitionTable self.headPosition = headPosition self.tape = {} for idx, character in enumerate(tape): self.tape[idx] = character def printTape(self): for key, value in sorted(self.tape.items()): if key == self.headPosition: print("[{0}]".format(value), end="") else: print(value, end="") def run(self): while (self.currentState not in self.stopState): self.printTape() noTransition = True symbol = self.tape[self.headPosition] for action in self.tansitionTable: if ((self.currentState == action["in"]["currentState"] and symbol == action["in"]["currentSymbol"]) or (self.currentState == action["in"]["currentState"] and action["in"]["currentSymbol"] == None)): print("({0}, {1}) => ({2}, {3}, {4})".format(self.currentState, symbol, action["out"]["newState"], action["out"]["newSymbol"], action["out"]["headMove"])) self.currentState = action["out"]["newState"] symbol = action["out"]["newSymbol"] move = action["out"]["headMove"] if symbol != "-": self.tape[self.headPosition] = symbol if move == "R": self.headPosition += 1 elif move == "L": self.headPosition -= 1 noTransition = False break if noTransition: print("No transition for (state,action) = ({0}, {1})".format(self.currentState, symbol)) break input("Press ENTER") self.printTape() print() def main(): initState = States.S stopState = [States.STOP, States.ACCEPT] tape = "abcabcabcabcabc" headPosition = 3 tm = TM(initState = initState, stopState = stopState, tansitionTable = tansitionTable, tape = tape, headPosition = headPosition) tm.run() if (__name__ == '__main__'): main()