import exceptions def convert_to_dict(table): ndict = {} for state in table: [ostate, read1, read2, nstate, write1, write2, move1, move2] = state.split(' ') ndict[(ostate, read1, read2)]=(nstate,write1, write2,move1, move2) return ndict def turing_machine(table, tape1, tape2): """ The turing machine table is implemented as a dictionary. The key is the current state and the current symbol under the read head. The value is the new state, the symbol to write and the move. I assume that I don't have to go left of the start position. """ if type(table)==type([]): table = convert_to_dict(table) tape1 = list(tape1) tape2 = list(tape2) state = "Start" index1 = 0 index2 = 0 print 'Each loop prints the state of the tapes, the current state of the machine and the new state of the machine.' print 'The current state of the machine includes: state, pos on tape 1, pos on tape 2, symbol on tape 1, symbol on tape 2.' print 'The new state of the machine includes: new state, symbol to write to tape 1, symbol to write to tape 2, how to move tape 1, how to move tape 2.' print "Tape1: ", tape1 print "Tape2: ", tape2 try: while state != "Accept" and state != "Reject" and index1>=0 and index2>=0: if index1>=len(tape1): tape1.append("B") if index2>=len(tape2): tape2.append("B") (new_state, write1, write2, move1, move2) = table[(state, tape1[index1], tape2[index2])] print 'Current machine state: ', state, index1, index2, tape1[index1], tape2[index2] print 'New machine state: ', new_state, write1, write2, move1, move2 if write1 != "": tape1[index1] = write1 if write2 != "": tape2[index2] = write2 if move1 == 'R': index1 += 1 elif move1 == 'L': index1 -= 1 if move2 == 'R': index2 += 1 elif move2 == 'L': index2 -= 1 state = new_state print "Tape1: ", tape1 print "Tape2: ", tape2 except Exception as e: print "Machine crashed: ", e print 'index1 = ', index1, ' index2 = ', index2 return False, tape1, tape2 return [state == 'Accept', tape1, tape2] def tm_2tape_copy(): """ This is an example two-tape TM that copies the input tape to the working tape. The table is a list of strings with each string of the form: "State read-t1 read-t2 New-state write-t1 write-t2 move-t1 move-t2" move-t1 and move-t2 are either L or R for left or right moves, or any other character for not moving the head (I use S). The machine only accepts by finishing in state called Accept. If there is no transition out of a state, or if the head runs off the left of the tape, or if the machine enters a Reject state, then it halts and rejects. It is possible for the machine to loop indefinitely. """ # table *is* the TM. Your answer should be in this form. table = [ "Start B B Copy B B R R", "Copy a B Copy a a R R", "Copy b B Copy b b R R", "Copy B B Accept B B R R" ] # this is some test code for the above machine accept, tape1, tape2 = turing_machine(table, "BababB", "BB") assert accept and tape1 == tape2 if __name__=='__main__': tm_2tape_copy()