I'm constructing part of a Turing Machine in Python 2.7.6. The method I'm using involves creating a state class and creating a new instance of the class for each state. Inside the states I have a blank dictionary that will store the transition functions.
class State:
name = ""
transitions = {}
def __init__(self, name):
self.name = name
def addTransition(self, symbol, transition):
self.transitions[symbol] = transition
Each instance of a state is held in a dictionary so that it can be easily referenced during initialization. This allows me to reference an object by opening the dictionary entry that has its name as a key
self.States[temp] = State(temp)
//temp is read from the tape, currently this is called twice with temp = q0 and q1
My problem arises when I try to add the transition functions to the internal dictionaries. When I add the record to one state, it adds it to the dictionary inside every state, creating an identical copy inside every state. Obviously, this becomes problematic.
def readTransitionTuple(self):
StateI = ''
StateF = ''
SymbolI = ''
SymbolF = ''
Action = ''
// Code reads input from tape here //
print (StateI, StateF, SymbolI, SymbolF, Action)
self.States[StateI].addTransition(SymbolI,(StateF, SymbolF, Action))
readTransitionTuple is called twice, and outputs these values for the variables:
('q0', 'q2', '0', '1', 'R')
('q1', 'q0', '1', '0', 'L')
When I try to print the transitions for state q0 it gives me this output:
{'1': ('q0', '0', 'L'), '0': ('q2', '1', 'R')}
If I try to print for q1 it is the same output. How can I assign a transition function to only one state instead of all of them? and what is causing this effect? My only thought is that it has to do with storing the states in a dictionary.