I'm trying to join the transition functions of 2 automatas, which are represented by 2 dictionaries of dictionaries
estados1 = ['A','B'] #Los estados del automata 1
estados2 = ['q1','q2','q3'] #Los estados del automata 2
estados_union = ['Aq1','Aq2','Aq3','Bq1','Bq2','Bq3'] #Los estados del autoata union
alfabeto = ['0','1'] #El alfabeto del automata union
The transition functions of automata 1 and 2, respectively
Where the key of the dictionary is a tuple with a state and an entry and its value is the state it leads to.
tf1[('A', '0')] = 'A'
tf1[('A', '1')] = 'B'
tf1[('B', '0')] = 'A'
tf1[('B', '1')] = 'B'
tf2 = dict()
tf2[('q1', '0')] = 'q3'
tf2[('q1', '1')] = 'q2'
tf2[('q2', '0')] = 'q2'
tf2[('q2', '1')] = 'q2'
tf2[('q3', '0')] = 'q2'
tf2[('q3', '1')] = 'q1'
I want to get a transition function 3, like this
tf3 = dict()
tf3[('Aq1', '0')] = 'Aq3'
tf3[('Aq1', '1')] = 'Bq2'
tf3[('Aq2', '0')] = 'Aq2'
tf3[('Aq2', '1')] = 'Aq2'
tf3[('Aq3', '0')] = 'Aq2'
tf3[('Aq3', '1')] = 'Aq2'
tf3[('Bq1', '0')] = 'Aq3'
tf3[('Bq1', '1')] = 'Bq2'
tf3[('Bq2', '0')] = 'Aq3'
tf3[('Bq2', '1')] = 'Bq2'
tf3[('Bq2', '0')] = 'Bq3'
tf3[('Bq3', '1')] = 'Bq2'
That is, I want to generate a dictionary where its key is made up of the elements of the automata_union and of each entry and its value is the result of the concatenation of the value of the states of automata 1 concatenated with the value of the states of automata 2, given an alphabet entry. For example, to generate the value of the transition function for state 'Aq1' with input 0, I would look up the value of ('A','0') in tf1, which is 'A', and look up the value from (q1,0) into tf2, which is 'q3'. Then then concatenate these values ('Aq3') and assign it to the corresponding key. ('Aq1',0) = 'Aq3' I hope I have explained myself well
So far I have the following code, but I have not achieved my goal
for i in range(len(estados_union)):
for j in range(len(alfabeto)):
estado_asociado = tf1[estados1[i],alfabeto[j]] + tf2[estados2[i],alfabeto[j]]
funcion_transicion_union[(estados_union[i],alfabeto[j])] = estado_asociado
I don't know if I got mixed up between state and state... But as you explain this should work:
The output is (ordering):
You can also generate the dictionary directly using list comprehensions, although there is less pythonic left:
I don't know if I'm confused or if your dictionary
tf3
doesn't correspond to the expected results when looking attf1
andtf2
. For example for('Aq2', '1')
we search('A', '1')
intf1
and we get'B'
but in your exampletf3
the output is'Aq2'
and not'Bq2'
.There is a very useful function for these cases,
product
, which performs the Cartesian product on a set of iterables. The equivalent of nesting loopsfor
.Or, with dict comprehension: