def main(): custom_TM = TuringMachine( { ('q0', '#'): ('End', '#', 'R'), ('End', ''): ('qa', '', 'R'), ('q0', '0'): ('q1', 'X', 'R'), ('q1', '#'): ('Check0', '#', 'R'), ('Check0', '0'): ('FindLeftmost', 'X', 'L'), ('q0', '1'): ('q2', 'X', 'R'), ('q2', '#'): ('Check1', '#', 'R'), ('Check1', '1'): ('FindLeftmost', 'X', 'L'), ('FindLeftmost', '0'): ('FindLeftmost', '0', 'L'), ('FindLeftmost', '1'): ('FindLeftmost', '1', 'L'), ('FindLeftmost', 'X'): ('FindLeftmost', 'X', 'L'), ('FindLeftmost', '#'): ('FindLeftmost', '#', 'L'), ('FindLeftmost', ''): ('FindNext', '', 'R'), ('FindNext', 'X'): ('FindNext', 'X', 'R'), ('FindNext', '0'): ('q1', 'X', 'R'), ('FindNext', '1'): ('q2', 'X', 'R'), ('FindNext', '#'): ('End', '#', 'R'), ('q1', '0'): ('q1', '0', 'R'), ('q1', '1'): ('q1', '1', 'R'), ('q2', '0'): ('q2', '0', 'R'), ('q2', '1'): ('q2', '1', 'R'), ('Check0', 'X'): ('Check0', 'X', 'R'), ('Check1', 'X'): ('Check1', 'X', 'R'), ('End', 'X'): ('End', 'X', 'R'), } ) user_input = str(input("Enter a word : ")) finish = False # use to check if the machine has reached a final state execution = custom_TM.run(user_input) while finish != True : context = next(execution) info =context[1] print("state : {0}".format(info["state"])) if(context[0] == "Reject" or context[0] == "Accept" ): finish = True print("\n***** Results *****") print("w = {0} ({1})".format(user_input,context[0] )) print("state : {0}".format(info["state"])) return 0
def main(): tm = TuringMachine(states={'i', 'a', 'b', 'c', 'd', 'e', 'H'}, symbols={'0', '1'}, blank_symbol='0', input_symbols={'1'}, initial_state='i', accepting_states={'H'}, transitions={ ('i', '0'): ('H', '0', 1), ('i', '1'): ('a', '0', 1), ('a', '1'): ('a', '1', 1), ('a', '0'): ('b', '0', 1), ('b', '1'): ('b', '1', 1), ('b', '0'): ('c', '1', 1), ('c', '0'): ('d', '1', -1), ('c', '0'): ('d', '1', -1), ('d', '1'): ('d', '1', -1), ('d', '0'): ('e', '0', -1), ('e', '1'): ('e', '1', -1), ('e', '0'): ('i', '0', 1), }) tm.initialize({i: '1' for i in range(5)}) # or a nicer way to input a string # tm.initialize(dict(enumerate("11111"))) while not tm.halted: tm.print() tm.step() time.sleep(.3) print(tm.accepted_input())
def main(): states_count = int(input()) states = [map(State, input().split())] state_initial, state_final = (map(State, input().split())) states_final = {state_final} steps_count = int(input()) steps = dict() while steps_count > 0: line = input() if line == '': continue steps_count -= 1 state, symbol, _, state_next, symbol_next, heading = line.split() state = State(state) state_next = State(state_next) heading = Heading(heading) steps[(state, symbol)] = (state_next, symbol_next, heading) tape = Tape(input()) machine = TuringMachine(tape=tape, alphabet=tape.get_alphabet(), empty='_', step_function=StepFunction(steps), states=states, state_initial=state_initial, states_final=states_final) while True: is_running = machine.make_step() if machine.is_final(): print(f'STOP after {machine.step_count} transitions') break if is_running: if machine.step_count >= 10**5: print(f'MADE 100000 transitions') break else: print(f'FAIL after {machine.step_count} transitions') break start = next((k for k, v in machine.tape.tape.items() if v != '_'), None) if start is not None: stop = next( (k for k, v in reversed(machine.tape.tape.items()) if v != '_'), None) tape = [] for i in range(start, stop + 1): tape.append(machine.tape.tape[i]) print(''.join(tape)) print(machine.state, machine.position - start) else: print() print(machine.state, 0)
class Maincontroller(object): """ Maincontroller() This class parses the input file, then create an instance of a Turing machine. Also is responsible to access a validate method of Turing machine and initialize your computing """ def __init__(self, file, tape_content): self._file_content = self._parse_file_(file) self._tape_content = tape_content self._turing_machine = TuringMachine(self._file_content, self._tape_content) def _parse_file_(self, file): file_content = [] try: with open(file, 'r') as f: for line in f: # Remove all leading and trailing characters (\n \r \t) of the line # Transforms the line into a list, spliting in ' ' # Then append the list in "file_content" file_content.append(line.strip().split(' ')) return file_content except IOError: print('Error opening file for reading.') print('The file exists and you have read permissions?') exit(1) def validate(self): """ validate() Input format validation. returns 0 if the input format is valid or one of the following for invalid: 1 if has no one input alphabet detected 2 if has no one tape alphabet detected 3 if has no one blank symbol detected 4 if has no one states detected 5 if has no one init state detected 6 if has no one final state detected 7 if the quantity of tapes is different of 1 8 if has no one transition detected """ return self._turing_machine.validate_input() def init_turing(self): """ Initialize the computing of Turing machine """ self._turing_machine.initialize_computing()
def main2(): tape1 = Tape('101011', '01') tape2 = Tape('', '01') states = [ State('qCopy', StateType.Start), State('qReturn', StateType.Empty), State('qTest', StateType.Empty), State('qa', StateType.Accept), State('qr', StateType.Reject) ] transitions = [ TransitionTwoTape('qCopy', '$', '$', 'qCopy', '$', '$', Direction.Right, Direction.Right), TransitionTwoTape('qCopy', '0', '#', 'qCopy', '0', '0', Direction.Right, Direction.Right), TransitionTwoTape('qCopy', '1', '#', 'qCopy', '1', '1', Direction.Right, Direction.Right), TransitionTwoTape('qCopy', '#', '#', 'qReturn', '#', '#', Direction.Neutral, Direction.Left), TransitionTwoTape('qReturn', '#', '0', 'qReturn', '#', '0', Direction.Neutral, Direction.Left), TransitionTwoTape('qReturn', '#', '1', 'qReturn', '#', '1', Direction.Neutral, Direction.Left), TransitionTwoTape('qReturn', '#', '$', 'qTest', '#', '$', Direction.Left, Direction.Right), TransitionTwoTape('qTest', '0', '0', 'qTest', '0', '0', Direction.Left, Direction.Right), TransitionTwoTape('qTest', '1', '1', 'qTest', '1', '1', Direction.Left, Direction.Right), TransitionTwoTape('qTest', '$', '#', 'qa', '$', '#', Direction.Neutral, Direction.Neutral), TransitionTwoTape('qTest', '1', '0', 'qr', '1', '0', Direction.Neutral, Direction.Neutral), TransitionTwoTape('qTest', '0', '1', 'qr', '0', '1', Direction.Neutral, Direction.Neutral) ] tm = TuringMachine(states, transitions, tape1, tape2) print( "\nTwo-tape Turing machine recognizes whether a binary string is a palindrome." ) tm.process2() print("\nInput string:") print(tm.get_tape1()) if (tm.current_state.type == StateType.Accept): print('\nAccepting') if (tm.current_state.type == StateType.Reject): print('\nRejecting') pass
def testPalindromeMachine(tape, initPos): # Machine quintuples q1 = Quintuple('s', 'a', BLANK, RIGHT, '1') # In state s, it scans the LHE, the left-hand-end. # If w starts with an 'a', does it end in an 'a'? q2 = Quintuple('1', 'a', 'a', RIGHT, '1') # In state 1, it moves to RHE q3 = Quintuple('1', 'b', 'b', RIGHT, '1') q4 = Quintuple('1', BLANK, BLANK, LEFT, '2') # and goes to state 2 q5 = Quintuple('2', 'a', BLANK, LEFT, '3') # In state 2, it checks that RHE = 'a' q6 = Quintuple('2', 'b', 'b', RIGHT, 'no') q7 = Quintuple('2', BLANK, BLANK, LEFT, 'yes') # was w = 'a'? [or was X = 'a'?] q8 = Quintuple('3', 'a', 'a', LEFT, '3') # In state 3, it moves back to LHE q9 = Quintuple('3', 'b', 'b', LEFT, '3') q10 = Quintuple('3', BLANK, BLANK, RIGHT, 's') # and starts again q11 = Quintuple('s', 'b', BLANK, RIGHT, '4') # If w starts with a 'b', does it end in a 'b'? q12 = Quintuple('4', 'a', 'a', RIGHT, '4') # In state 4, it moves to RHE q13 = Quintuple('4', 'b', 'b', RIGHT, '4') q14 = Quintuple('4', BLANK, BLANK, LEFT, '5') q15 = Quintuple('5', 'a', 'a', RIGHT, 'no') # In state 5, it checks that RHE = 'b' q16 = Quintuple('5', 'b', BLANK, LEFT, '3') q17 = Quintuple('5', BLANK, BLANK, LEFT, 'yes') # was w = 'b'? [or was X = 'b'?] q18 = Quintuple('s', BLANK, BLANK, RIGHT, 'yes') # Is the word with no letters a palindrome? quintuples = [ q1, q2, q3, q4, q5, q6, q7, q8, q9, q10, q11, q12, q13, q14, q15, q16, q17, q18 ] tapeCopy = tape.copy() machine = TuringMachine(quintuples, 's', ['yes', 'no']) machine.run(tape, initPos) print('Palindrome machine, input was: ', tapeCopy, ', if palyndrome then state = yes\n')
def testDecimalSuccessorMachine(tape, initPos): # Machine quintuples q1 = Quintuple('s', 0, 0, RIGHT, 's') # In state s, it moves to RHE, the right-hand-end q2 = Quintuple('s', 1, 1, RIGHT, 's') # of the string of nonblank symbols q3 = Quintuple('s', 2, 2, RIGHT, 's') q4 = Quintuple('s', 3, 3, RIGHT, 's') q5 = Quintuple('s', 4, 4, RIGHT, 's') q6 = Quintuple('s', 5, 5, RIGHT, 's') q7 = Quintuple('s', 6, 6, RIGHT, 's') q8 = Quintuple('s', 7, 7, RIGHT, 's') q9 = Quintuple('s', 8, 8, RIGHT, 's') q10 = Quintuple('s', 9, 9, RIGHT, 's') q11 = Quintuple('s', BLANK, BLANK, LEFT, 't') # When it goes past the RHE, it steps left # and goes to state t q12 = Quintuple('t', 0, 1, LEFT, 'h') # In state t, it adds 1 to current digit and halts q13 = Quintuple('t', 1, 2, LEFT, 'h') q14 = Quintuple('t', 2, 3, LEFT, 'h') q15 = Quintuple('t', 3, 4, LEFT, 'h') q16 = Quintuple('t', 4, 5, LEFT, 'h') q17 = Quintuple('t', 5, 6, LEFT, 'h') q18 = Quintuple('t', 6, 7, LEFT, 'h') q19 = Quintuple('t', 7, 8, LEFT, 'h') q20 = Quintuple('t', 8, 9, LEFT, 'h') q21 = Quintuple('t', 9, 0, LEFT, 't') # But if the current digit is 9, it "carries one" q22 = Quintuple('t', BLANK, 1, LEFT, 'h') # for when the input is all 9's quintuples = [ q1, q2, q3, q4, q5, q6, q7, q8, q9, q10, q11, q12, q13, q14, q15, q16, q17, q18, q19, q20, q21, q22 ] tapeCopy = tape.copy() machine = TuringMachine(quintuples, 's', ['h']) machine.run(tape, initPos) print('Decimal succesor machine, input was: ', tapeCopy, '\n')
def increment(word, verbose=False): tape = Tape(word, '|') states = [ State("s0", StateType.Start), State("s1", StateType.Empty), State("sf", StateType.Final) ] transitions = [ Transition("s0", "$", "s1", "$", Direction.Right), Transition("s1", "|", "s1", "|", Direction.Right), Transition("s1", "#", "sf", "|", Direction.Neutral) ] return TuringMachine(states, transitions, tape, verbose)
def run_turing(tf, init, final): initial_state = init, accepting_states = final, transition_function = tf final_states = {"final"} t = TuringMachine("010011 ", initial_state=init, final_states=final, transition_function=tf) print("Input on Tape:\n" + t.get_tape()) while not t.final(): t.step() return t.get_tape()
def subtract(word, verbose=False): tape = Tape(word, '|&') states = [ State("s0", StateType.Start), State("s1", StateType.Empty), State("s2", StateType.Empty), State("s3", StateType.Empty), State("s4", StateType.Empty), State("s5", StateType.Empty), State("s6", StateType.Empty), State("s7", StateType.Empty), State("s8", StateType.Empty), State("sf", StateType.Final) ] transitions = [ Transition("s0", "$", "s0", "$", Direction.Right), Transition("s0", "#", "sf", "#", Direction.Neutral), Transition("s0", "|", "s1", "|", Direction.Right), Transition("s1", "|", "s1", "|", Direction.Right), Transition("s1", "#", "s2", "#", Direction.Right), Transition("s2", "#", "s2", "#", Direction.Right), Transition("s2", "|", "s3", "|", Direction.Right), Transition("s3", "|", "s4", "|", Direction.Left), Transition("s3", "#", "s6", "#", Direction.Left), Transition("s4", "|", "s5", "#", Direction.Left), Transition("s5", "#", "s5", "#", Direction.Left), Transition("s5", "|", "s2", "#", Direction.Right), Transition("s5", "$", "s2", "$", Direction.Right), Transition("s6", "|", "s7", "#", Direction.Left), Transition("s7", "#", "s7", "#", Direction.Left), Transition("s7", "$", "sf", "$", Direction.Neutral), Transition("s7", "|", "s8", "#", Direction.Left), Transition("s8", "|", "s8", "|", Direction.Left), Transition("s8", "$", "sf", "$", Direction.Neutral) ] return TuringMachine(states, transitions, tape, verbose)
tape = Tape(word, "10x") states = [ State("s0", StateType.Start), State("s1", StateType.Empty), State("s2", StateType.Empty), State("s3", StateType.Empty), State("s4", StateType.Empty), #getting rid of x in tape State("sf", StateType.Final) ] transitions = [ Transition('s0', '$', 's0', '$', Direction.Right), Transition('s0', '1', 's1', 'x', Direction.Left), Transition('s1', '$', 's2', '1', Direction.Right), Transition('s2', '1', 's2', '1', Direction.Right), Transition('s2', '0', 's2', '0', Direction.Right), Transition('s2', 'x', 's3', 'x', Direction.Right), Transition('s3', 'x', 's3', 'x', Direction.Right), Transition('s3', '1', 's1', 'x', Direction.Left), Transition('s1', '1', 's1', '0', Direction.Left), Transition('s1', 'x', 's1', 'x', Direction.Left), Transition('s1', '0', 's2', '1', Direction.Right), Transition('s3', '#', 's4', '#', Direction.Left), #clearing x Transition('s4', 'x', 's4', '#', Direction.Left), Transition('s4', '1', 'sf', '1', Direction.Neutral), Transition('s4', '0', 'sf', '0', Direction.Neutral), ] tm = TuringMachine(states, transitions, tape) tm.process(verbose=False) print("FINAL TAPE: " + tm.get_tape())
# This means that you could construct a Turing Machine lazily, repeatedly # ask for output with next, _only when needed_, or collect all its outputs # if needed # # EXAMPLE: # >>> x = (i ** 2 for i in range(1, 10)) # >>> list(x) # [1, 4, 9, 16, 25, 36, 49, 64, 81] #create the Turing machine bbeaver2 = TuringMachine( { ('a', '0'): ('b', '1', 'R'), ('a', '1'): ('b', '1', 'L'), ('b', '0'): ('a', '1', 'L'), ('b', '1'): ('h', '1', 'R'), }, start_state='a', accept_state='h', reject_state='r', blank_symbol='0' ) bbeaver3 = TuringMachine( { ('a', '0'): ('b', '1', 'R'), ('a', '1'): ('b', '1', 'L'), ('b', '0'): ('a', '1', 'L'), ('b', '1'): ('c', '1', 'R'), ('c', '0'): ('h', '1', 'R'), ('c', '1'): ('h', '1', 'R'), }, start_state='a', accept_state='h', reject_state='r', blank_symbol='0'
scheme = TuringMachine( { # setup string ('q0',''):('w0','#','R'), ('w0',''):('w1','1','R'), ('w1',''):('w+','1','R'), ('w+',''):('w2','+','R'), ('w2',''):('w3','1','R'), ('w3',''):('w4','1','R'), ('w4',''):('w5','1','R'), ('w5',''):('w=','1','R'), ('w=',''):('leftMost','=','L'), ('q1','1'):('rightMost','x','R'), ('q1','+'):('q1','x','R'), ('q1','='):('qa','=','R'), ('rightMost','1'):('rightMost','1','R'), ('rightMost','+'):('rightMost','+','R'), ('rightMost','='):('rightMost','=','R'), ('rightMost',''):('leftMost','1','L'), ('leftMost','1'):('leftMost','1','L'), ('leftMost','+'):('leftMost','+','L'), ('leftMost','='):('leftMost','=','L'), ('leftMost','x'):('q1','x','R'), ('leftMost','#'):('q1','#','R'), } )
from turing_machine import TuringMachine initial_state = "init", accepting_states = ["final"], transition_function = { ("init", "0"): ("init", "1", "R"), ("init", "1"): ("init", "0", "R"), ("init", " "): ("final", " ", "N"), } final_states = {"final"} t = TuringMachine("BB0100100110011000110001BB", initial_state="init", final_states=final_states, transition_function=transition_function) print("Input on Tape:\n" + t.get_tape()) while not t.final(): t.step() print("Result of the Turing machine calculation:") print(t.get_tape())
from turing_machine import TuringMachine from state import State, StateType from transition import Transition from direction import Direction from tape import Tape tape = Tape('aaabbb', 'abxy') states = [ State("s0", StateType.Start), State("s1", StateType.Empty), State("s2", StateType.Empty), State("sf", StateType.Final) ] transitions = [ Transition("s0", "$", "s0", "$", Direction.Right), Transition("s0", "a", "s1", "x", Direction.Right), Transition("s1", "a", "s1", "a", Direction.Right), Transition("s1", "b", "s2", "y", Direction.Left), Transition("s2", "a", "s2", "a", Direction.Left), Transition("s2", "x", "s0", "x", Direction.Right), Transition("s1", "y", "s1", "y", Direction.Right), Transition("s2", "y", "s2", "y", Direction.Left), Transition("s0", "y", "sf", "y", Direction.Neutral) ] tm = TuringMachine(states, transitions, tape) tm.process(verbose=True) print(tm.get_tape())
accepting_states = ["final", "A", "B", "C", "D", "E", "F"], transition_function = { ("A", "0"): ("B", "1", "R"), ("A", "1"): ("D", "0", "L"), ("B", "0"): ("C", "1", "R"), ("B", "1"): ("F", "0", "R"), ("C", "0"): ("C", "1", "L"), ("C", "1"): ("A", "1", "L"), ("D", "0"): ("E", "0", "L"), ("D", "1"): ("A", "1", "R"), ("E", "0"): ("A", "1", "L"), ("E", "1"): ("B", "0", "R"), ("F", "0"): ("C", "0", "R"), ("F", "1"): ("E", "0", "R"), } final_states = {"final"} t = TuringMachine( "00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", initial_state="A", final_states=final_states, transition_function=transition_function) print("Input on Tape:\n" + t.get_tape()) for i in range(1230229): t.step() print("Result of the Turing machine calculation:") print(t.get_tape())
def testBinaryAdderMachine(tape, initPos): # Machine quintuples q1 = Quintuple('s', 0, 0, RIGHT, 's') # In state s, it moves to RHE q2 = Quintuple('s', 1, 1, RIGHT, 's') q3 = Quintuple('s', 'a', 'a', RIGHT, 's') # Latter, there will be a's and b's in the summand q4 = Quintuple('s', 'b', 'b', RIGHT, 's') q5 = Quintuple('s', '+', '+', RIGHT, 's') q6 = Quintuple('s', BLANK, BLANK, LEFT, '1') q7 = Quintuple('1', 0, BLANK, LEFT, '2') # In state 1, it finds x = 0 # We'll do the other cases for x later q8 = Quintuple('2', 0, 0, LEFT, '2') # In state 2, it moves left across 0 and 1 to + q9 = Quintuple('2', 1, 1, LEFT, '2') q10 = Quintuple('2', '+', '+', LEFT, '3') q11 = Quintuple('3', 'a', 'a', LEFT, '3') # In state 3, it moves left across a and b to y q12 = Quintuple('3', 'b', 'b', LEFT, '3') q13 = Quintuple('3', 0, 'a', RIGHT, 's') # y = 0, and x + y = 0, but this is recorded as a # Then, we move right to get the next x q14 = Quintuple('3', BLANK, 'a', RIGHT, 's') # When there is no corresponding bit y because the # summand is shorter than the addend, we take 0 for # y and record an a and move right to get the next x q15 = Quintuple('3', 1, 'b', RIGHT, 's') # y = 1 and x + y = 1, but this is recorded as b # Then, we move right to get the next x q16 = Quintuple('1', 1, BLANK, LEFT, '4') # In state 1, it finds x = 1 q17 = Quintuple('4', 0, 0, LEFT, '4') # In state 4, it move left across 0 and 1 to + q18 = Quintuple('4', 1, 1, LEFT, '4') q19 = Quintuple('4', '+', '+', LEFT, '5') q20 = Quintuple('5', 'a', 'a', LEFT, '5') # In state 5, it moves left across a and b to y q21 = Quintuple('5', 'b', 'b', LEFT, '5') q22 = Quintuple('5', '0', 'b', RIGHT, 's') # y = 0 and x + y = 1, but this is recorded as b # Then, we move right to get the next x q23 = Quintuple('5', BLANK, 'b', RIGHT, 's') # When there is no corresponding bit y, take 0 for y # and record a 'b' and move right to get the next x q24 = Quintuple('5', 1, 'a', LEFT, '6') # y = 1 and x + y = 10, but this is recorded as a # Then, we move to state 6 and carry the one q25 = Quintuple('6', 0, 1, RIGHT, 's') q26 = Quintuple('6', BLANK, 1, RIGHT, 's') q27 = Quintuple('6', 1, 0, LEFT, '6') q28 = Quintuple('1', '+', BLANK, LEFT, '7') # In state 1, it finds no x q29 = Quintuple('7', 'a', 0, LEFT, '7') # In state 7, it replaces a's by 0s q30 = Quintuple('7', 'b', 1, LEFT, '7') # and it replaces b's by 1s q31 = Quintuple('7', 0, 0, LEFT, '7') # moves to the LHE q32 = Quintuple('7', 1, 1, LEFT, '7') q33 = Quintuple('7', BLANK, BLANK, RIGHT, 'h') # and halts quintuples = [ q1, q2, q3, q4, q5, q6, q7, q8, q9, q10, q11, q12, q13, q14, q15, q16, q17, q18, q19, q20, q21, q22, q23, q24, q25, q26, q27, q28, q29, q30, q31, q32, q33 ] tapeCopy = tape.copy() machine = TuringMachine(quintuples, 's', ['h']) machine.run(tape, initPos) print('Binary adder machine, input was: ', tapeCopy, '\n')
# -*- coding: utf-8 -*- """ Test script for running a Turing machine unary adder Created on Fri Mar 29 21:57:42 2019 @author: shakes """ from turing_machine import TuringMachine #create the Turing machine adder = TuringMachine({ #Write your transition rules here as entries to a Python dictionary #For example, the key will be a pair (state, character) #The value will be the triple (next state, character to write, move head L or R) #such as ('q0', '1'): ('q1', '0', 'R'), which says if current state is q0 and 1 encountered #then transition to state q1, write a 0 and move head right. ('q0', '1'): ('q0', '1', 'R'), ('q0', '0'): ('q0', '', 'R'), ('q0', ''): ('qa', '', 'R') }) print("Input:", '110111') print("Accepted?", adder.accepts('110111')) adder.debug('110111') print("Input:", '11101111') print("Accepted?", adder.accepts('11101111')) adder.debug('11101111')
multiplier = TuringMachine({ #'b' determines the tally we'll be applying it to those will get removed at the end but also #'a' the tallies on the right side we've already done and also the tallies we've manually placed #'X' the left end, treat it like another 1 #'B' the left end, treat it like another b #0. Set left end to 'X' go to the right end #1. Turn first tally into 'a' then go to the left #2. Find first tally after 0 #3. Set this tally to 'b' then go back right #4. Go all the way to the right and enter 'b' at the first empty space #5. Repeat 3 and 4 until the left side hits 'X' #5.5 Replace all 'b's on the left with 1s #6. Find the next tally and repeat from step 1 #7. Stop once you can't find a tally (you hit the 0) #8. Clear left then clear right until you hit empty or 'b' ('q0', '1'): ('FindRightEnd', 'X', 'R'), ('q0', '0'): ('ClearRight', '', 'R'), ('FindRightEnd', '1'): ('FindRightEnd', '1', 'R'), ('FindRightEnd', '0'): ('FindRightEnd', '0', 'R'), ('FindRightEnd', ''): ('CheckLeftTally', '', 'L'), ('FindRightEnd', 'a'): ('CheckLeftTally', 'a', 'L'), ('CheckLeftTally', '0'): ('ClearFromLeft', '0', 'L'), ('CheckLeftTally', '1'): ('GetToZero', 'a', 'L'), ('GetToZero', '1'): ('GetToZero', '1', 'L'), ('GetToZero', 'a'): ('GetToZero', 'a', 'L'), ('GetToZero', 'b'): ('GetToZero', 'b', 'L'), ('GetToZero', '0'): ('FindLHSTally', '0', 'L'), ('FindLHSTally', '1'): ('AddTally', 'b', 'R'), ('FindLHSTally', 'b'): ('FindLHSTally', 'b', 'L'), ('FindLHSTally', 'X'): ('AddTally', 'B', 'R'), ('FindLHSTally', 'B'): ('BsToOnes', 'X', 'R'), ('AddTally', '1'): ('AddTally', '1', 'R'), ('AddTally', '0'): ('AddTally', '0', 'R'), ('AddTally', 'b'): ('AddTally', 'b', 'R'), ('AddTally', 'a'): ('AddTally', 'a', 'R'), ('AddTally', ''): ('GetToZero', 'b', 'L'), ('ClearFromLeft', '1'): ('ClearFromLeft', '1', 'L'), ('ClearFromLeft', 'X'): ('ClearRight', '', 'R'), ('ClearRight', 'a'): ('ClearRight', '', 'R'), ('ClearRight', '1'): ('ClearRight', '', 'R'), ('ClearRight', '0'): ('ClearRight', '', 'R'), ('ClearRight', 'b'): ('BsToOnes', '1', 'R'), ('ClearRight', ''): ('qa', '', 'R'), ('BsToOnes', 'b'): ('BsToOnes', '1', 'R'), ('BsToOnes', '0'): ('FindRightEnd', '0', 'R'), ('BsToOnes', ''): ('qa', '', 'R'), #Write your transition rules here as entries to a Python dictionary #For example, the key will be a pair (state, character) #The value will be the triple (next state, character to write, move head L or R) #such as ('q0', '1'): ('q1', '0', 'R'), which says if current state is q0 and 1 encountered #then transition to state q1, write a 0 and move head right. })
('FindLeftmost', 'X'): ('FindLeftmost', 'X', 'L'), ('FindLeftmost', '#'): ('FindLeftmost', '#', 'L'), ('FindLeftmost', ''): ('FindNext', '', 'R'), ('FindNext', 'X'): ('FindNext', 'X', 'R'), ('FindNext', '0'): ('FindDelimiter0', 'X', 'R'), ('FindNext', '1'): ('FindDelimiter1', 'X', 'R'), ('FindNext', '#'): ('End', '#', 'R'), ('End', 'X'): ('End', 'X', 'R') } if __name__ == "__main__": print_transitions(transitions) machine = TuringMachine(transitions) def run(input_): w = input_ print("Input:",w) print("Accepted" if machine.accepts(w) else "Rejected") machine.debug(w) print() # ACCEPTS run("#") # REJECTS - the first character is a 0 # and the character at the end of the 1s is a 1 run("0000#XXXX1")
from turing_machine import TuringMachine machine = TuringMachine({ ('q0', '#'): ('End', '#', 'R'), ('End', ''): ('qa', '', 'R'), ('q0', '0'): ('FindDelimiter0', 'X', 'R'), ('FindDelimiter0', '#'): ('Check0', '#', 'R'), ('Check0', '0'): ('FindLeftmost', 'X', 'L'), ('q0', '1'): ('FindDelimiter1', 'X', 'R'), ('FindDelimiter1', '#'): ('Check1', '#', 'R'), ('Check1', '1'): ('FindLeftmost', 'X', 'L'), ('FindLeftmost', '0'): ('FindLeftmost', '0', 'L'), ('FindLeftmost', '1'): ('FindLeftmost', '1', 'L'), ('FindLeftmost', 'X'): ('FindLeftmost', 'X', 'L'), ('FindLeftmost', '#'): ('FindLeftmost', '#', 'L'), ('FindLeftmost', ''): ('FindNext', '', 'R'), ('FindNext', 'X'): ('FindNext', 'X', 'R'), ('FindNext', '0'): ('FindDelimiter0', 'X', 'R'), ('FindNext', '1'): ('FindDelimiter1', 'X', 'R'), ('FindNext', '#'): ('End', '#', 'R'), ('FindDelimiter0', '0'): ('FindDelimiter0', '0', 'R'), ('FindDelimiter0', '1'): ('FindDelimiter0', '1', 'R'), ('FindDelimiter1', '0'): ('FindDelimiter1', '0', 'R'), ('FindDelimiter1', '1'): ('FindDelimiter1', '1', 'R'), ('Check0', 'X'): ('Check0', 'X', 'R'), ('Check1', 'X'): ('Check1', 'X', 'R'), ('End', 'X'): ('End', 'X', 'R') }) w = "1#1#00#100#100" #try some strings here to find out what the machine accepts and rejects print("Input:", w)
from turing_machine import TuringMachine two = TuringMachine({ ('q0', '0'): ('Expect0', 'd', 'R'), ('q0', '1'): ('Expect1', 'd', 'R'), ('Expect0', '0'): ('Expect0', '0', 'R'), ('Expect0', '1'): ('Expect0', '1', 'R'), ('Expect0', '#'): ('Need0', '#', 'R'), ('Expect1', '0'): ('Expect1', '0', 'R'), ('Expect1', '1'): ('Expect1', '1', 'R'), ('Expect0', '#'): ('Need0', '#', 'R'), ('Expect0', '#'): ('Need0', '#', 'R'), }) multiplier.debug('111#111', step_limit=300) # output 1111111111
from turing_machine import TuringMachine from state import State, StateType from transition import Transition from direction import Direction from tape import Tape # Simple test to check whether the turing machine is working tape = Tape('|||', '|') states = [ State("s0", StateType.Start), State("s1", StateType.Empty), State("sf", StateType.Final) ] transitions = [ Transition("s0", "$", "s1", "$", Direction.Right), Transition("s1", "|", "s1", "|", Direction.Right), Transition("s1", "#", "sf", "|", Direction.Neutral) ] tm = TuringMachine(states, transitions, tape) tm.process() print(tm.get_tape())
(s1, _) = start (s2, _, _) = finish states.add(s1) states.add(s2) print("The Turing machine has", len(states), "states:") for i in states: print(i) print() if __name__ == "__main__": print_states(transitions) machine = TuringMachine(transitions) def run(input_): w = input_ print("Input:", w) print("Accepted" if machine.accepts(w) else "Rejected") machine.debug(w) print() # SHOULD ACCEPT run("##") # SHOULD REJECT run("101031##") # SHOULD REJECT
multiplier = TuringMachine({ #Write your transition rules here as entries to a Python dictionary #For example, the key will be a pair (state, character) #The value will be the triple (next state, character to write, move head L or R) #such as ('q0', '1'): ('q1', '0', 'R'), which says if current state is q0 and 1 encountered #then transition to state q1, write a 0 and move head right. ('q0', '1'): ('q2', '#', 'R'), ('q2', '1'): ('q2', '1', 'R'), ('q2', '0'): ('q3', '#', 'R'), ('q2', '#'): ('q3', '#', 'R'), ('q3', '1'): ('q4', '#', 'R'), ('q3', '0'): ('q15', '#', 'L'), ('q3', '#'): ('q4', '#', 'R'), ('q4', '1'): ('q4', '1', 'R'), ('q4', ''): ('q5', '#', 'R'), ('q4', '#'): ('q5', '#', 'R'), ('q5', '1'): ('q5', '1', 'R'), ('q5', ''): ('q6', '1', 'L'), ('q6', '#'): ('q7', '#', 'L'), ('q6', '1'): ('q6', '1', 'L'), ('q7', '#'): ('q9', '1', 'L'), ('q7', '1'): ('q8', '1', 'L'), ('q8', '#'): ('q3', '1', 'R'), ('q8', '1'): ('q8', '1', 'L'), ('q9', '#'): ('q10', '#', 'L'), ('q9', '1'): ('q9', '1', 'L'), ('q10', '#'): ('q12', '', 'R'), ('q10', '1'): ('q11', '1', 'L'), ('q11', '#'): ('q0', '', 'R'), ('q11', '1'): ('q11', '1', 'L'), ('q12', '#'): ('q12', '', 'R'), ('q12', '1'): ('q13', '#', 'R'), ('q13', '#'): ('q14', '', 'L'), ('q13', '1'): ('q13', '#', 'R'), ('q13', ''): ('qa', '', 'L'), ('q14', '#'): ('q14', '', 'L'), ('q14', '1'): ('q14', '#', 'R'), ('q14', ''): ('qa', '', 'L'), ## ('q14', '0'): ('q14','#','R'), ('q15', '#'): ('q16', '', 'L'), ('q15', '1'): ('q15', '#', 'L'), ('q15', ''): ('qa', '', 'L'), ## ('q15', '0'): ('q15','#','L'), ('q16', '#'): ('qa', '', 'L'), ('q16', ''): ('qa', '', 'L'), ('q16', '1'): ('q16', '#', 'L'), ## ('q16', '0'): ('q16','#','L'), })
from turing_machine import TuringMachine transition_function = {("init","0"):("init", "1", "R"), ("init","1"):("init", "0", "R"), ("init"," "):("final"," ", "N"), } t = TuringMachine("010011 ", final_states=["final"], transition_function=transition_function) print("Input on Tape:") print(t.get_tape_str()) while not t.final(): t.step() print("Result of the Turing machine calculation:") print(t.get_tape_str())
from turing_machine import TuringMachine machine = TuringMachine({ ('q0', '#'): ('saw_#', '#', 'R'), ('saw_#', '#'): ('saw_##', '#', 'R'), ('saw_##', ''): ('qa', '', 'R'), }) w = "##" #try some strings here to find out what the machine accepts and rejects print("Input:", w) print("Accepted?", machine.accepts(w)) machine.debug(w)
("0.011.100.01000", True), ("1.010.11.001000", True), ("0000.10.0100.10000", True), ("10.011.1100", True), ("1.000.10", False), ("110.111.11", False), ("0.000", False), ("000.01", False), ("100.110.000", False), ] if __name__ == "__main__": folder = 'input_machines' timeout = 8 for filename in listdir(folder): filepath = f"{folder}/{filename}" username = filename.upper().split(".TXT")[0] tm = TuringMachine.from_file(filepath) print(username, end="\t") for word, expected in TESTS: result = tm.run(word, timeout=timeout) value = "1" if result is expected else "0" print(value, end="\t") for word, expected in BONUS_TESTS: result = tm.run(word, timeout=timeout) value = "1" if result is expected else "0" print(value, end="\t") print()
# -*- coding: utf-8 -*- """ Busy beaver Turing machine with 2 states. Created on Sat Mar 30 13:55:25 2019 @author: shakes """ from turing_machine import TuringMachine #create the Turing machine bbeaver = TuringMachine( { #Write your transition rules here as entries to a Python dictionary #For example, the key will be a pair (state, character) #The value will be the triple (next state, character to write, move head L or R) #such as ('q0', '1'): ('q1', '0', 'R'), which says if current state is q0 and 1 encountered #then transition to state q1, write a 0 and move head right. ('a', '0'):('b','1','R'), ('a', '1'):('b','1','L'), ('b', '0'):('a','1','L'), ('b', '1'):('h','1','R'), }, start_state='a', accept_state='h', reject_state='r', blank_symbol='0' ) bbeaver.debug('00000000000000', step_limit=1000)
Created on Fri Mar 29 21:57:42 2019 @author: shakes """ from turing_machine import TuringMachine #create the Turing machine adder = TuringMachine( { #('q0', '0'): ('qa', ' ', 'R'), #('q0', '1'): ('q0', '1', 'R'), #('q0', ''): ('qr', '', 'R'), ('q0', '0'): ('CheckRight', '0', 'R'), ('CheckRight', ''): ('Delete0', '', 'L'), ('Delete0', '0'): ('qa', '', 'R'), ('CheckRight', '1'): ('Swap0', '0', 'L'), ('Swap0', '0'): ('q0', '1', 'R'), ('q0', '1'): ('q0', '1', 'R') #Write your transition rules here as entries to a Python dictionary #For example, the key will be a pair (state, character) #The value will be the triple (next state, character to write, move head L or R) #such as ('q0', '1'): ('q1', '0', 'R'), which says if current state is q0 and 1 encountered #then transition to state q1, write a 0 and move head right. } ) adder.debug('111011111')
from turing_machine import TuringMachine transition_function = { ("init", "0"): ("init", "1", "R"), ("init", "1"): ("init", "0", "R"), ("init", " "): ("final", " ", "N"), } t = TuringMachine("010011 ", final_states=["final"], transition_function=transition_function) print("Input on Tape:") print(t.get_tape_str()) while not t.final(): t.step() print("Result of the Turing machine calculation:") print(t.get_tape_str())
from turing_machine import TuringMachine tm = TuringMachine.from_file("oddbinarymachine.txt") result = tm.run("11010") print('result = tm.run("11010") # result =', result) state = tm.current_state print('state = tm.current_state # state =', state) tape_content = tm.tapes.words[0] print('tape_content = tm.tapes.words[0] # tape_content =', tape_content) tm.print_current_configuration()
args = parser.parse_args() step = args.step verbose = args.verbose with open(args.config + ".conf", 'r') as config_f: config = ast.literal_eval(config_f.read()) if args.tapes: config['tapesInput'] = args.tapes.split(',') else: config['tapesInput'] = str(raw_input("content of tapes? ")).split(" ") # ******************************** # run turing machine # ******************************** t = TuringMachine(**config) print t while t.step(): # next step with enter if step: raw_input() if verbose: print t char = '0' print "{0} occurs {1} times".format(char, t.getCount(char)) print "Steps: {0}".format(t.getStepCount())
w_hash_w = TuringMachine( { ('q0', '#'): ('End', '#', 'R'), ('End', ''): ('qa', '', 'R'), ('q0', '0'): ('FindDelimiter0', 'X', 'R'), ('FindDelimiter0', '#'): ('Check0', '#', 'R'), ('Check0', '0'): ('FindLeftmost', 'X', 'L'), ('q0', '1'): ('FindDelimiter1', 'X', 'R'), ('FindDelimiter1', '#'): ('Check1', '#', 'R'), ('Check1', '1'): ('FindLeftmost', 'X', 'L'), ('FindLeftmost', '0'): ('FindLeftmost', '0', 'L'), ('FindLeftmost', '1'): ('FindLeftmost', '1', 'L'), ('FindLeftmost', 'X'): ('FindLeftmost', 'X', 'L'), ('FindLeftmost', '#'): ('FindLeftmost', '#', 'L'), ('FindLeftmost', ''): ('FindNext', '', 'R'), ('FindNext', 'X'): ('FindNext', 'X', 'R'), ('FindNext', '0'): ('FindDelimiter0', 'X', 'R'), ('FindNext', '1'): ('FindDelimiter1', 'X', 'R'), ('FindNext', '#'): ('End', '#', 'R'), ('FindDelimiter0', '0'): ('FindDelimiter0', '0', 'R'), ('FindDelimiter0', '1'): ('FindDelimiter0', '1', 'R'), ('FindDelimiter1', '0'): ('FindDelimiter1', '0', 'R'), ('FindDelimiter1', '1'): ('FindDelimiter1', '1', 'R'), ('Check0', 'X'): ('Check0', 'X', 'R'), ('Check1', 'X'): ('Check1', 'X', 'R'), ('End', 'X'): ('End', 'X', 'R') } )