Prerequisite: Designing finite automata
In this article, we will see a designing of Deterministic Finite Automata (DFA).
Problem: Construction of a minimal DFA accepting set of strings over {a, b} in which Number of a(w) mod 2 = 0 or Number of b(w) mod 2 = 0 i.e, number of ‘a’ should be divisible by 2 or number of ‘b’ should be divisible by 2 or both are divisible by 2, where ‘w’ is the any string over {a, b}.
Explanation: The desired language will be like:
L1 = {ε, aa, aabb, aab, bb, bba, ...........}
Here as we can see that each string of the above language are satisfying the condition of the given problem i.e, here ε is accepted because the number of ‘a’ and ‘b’ both are zero and rest of the strings are having ‘a’ divisible by 2 or ‘b’ divisible by 2 or both are divisible by 2.
But the below language is not accepted by this DFA because it’s strings are not satisfying the condition of the given problem.
L2 = {ba, bbba, baaa, ..............}
Here as we can see that none of the strings of the above language is satisfying the condition of the given problem i.e, either ‘a’ or ‘b’ or both of any of the above strings are not divisible by 2.
The state transition diagram of the desired language will be like below:

In the above DFA, In each state there is a state name as ‘A’ and just below of it there is (ee) which indicates the number of ‘a’ is even (e) and number of ‘b’ is even (e) too. For state name as ‘B’ and just below of it there is (eo) which indicates the number of ‘a’ is even (e) and number of ‘b’ is odd (o) and so on.
- The initial and final state ‘A’ on getting ‘a’ as the input it transits to a final state ‘D’ and on getting ‘b’ as the input it transits to an another final state ‘B’.
- The final state ‘B’ on getting ‘a’ as the input it transits to a state ‘C’ and on getting ‘b’ as the input returns back to the initial state ‘A’.
- The another final state ‘D’ on getting ‘b’ as the input it transits to a state ‘C’ and on getting ‘a’ as the input it returns back to the initial state ‘A’.
- The state ‘C’ on getting ‘b’ as the input it transits to the final state ‘D’ and on getting ‘a’ as the input it returns back to the state ‘B’.
Python Implementation:
def stateA(n):
if ( len (n) = = 0 ):
print ( "string accepted" )
else :
if (n[ 0 ] = = 'a' ):
stateD(n[ 1 :])
elif (n[ 0 ] = = 'b' ):
stateB(n[ 1 :])
def stateB(n):
if ( len (n) = = 0 ):
print ( "string accepted" )
else :
if (n[ 0 ] = = 'a' ):
stateC(n[ 1 :])
elif (n[ 0 ] = = 'b' ):
stateA(n[ 1 :])
def stateC(n):
if ( len (n) = = 0 ):
print ( "string not accepted" )
else :
if (n[ 0 ] = = 'a' ):
stateB(n[ 1 :])
elif (n[ 0 ] = = 'b' ):
stateD(n[ 1 :])
def stateD(n):
if ( len (n) = = 0 ):
print ( "string accepted" )
else :
if (n[ 0 ] = = 'a' ):
stateA(n[ 1 :])
elif (n[ 0 ] = = 'b' ):
stateC(n[ 1 :])
n = input ()
stateA(n)
|