This is an old revision of the document!


2. Deterministic finite automata

Python supports a limited version of Object-Oriented programming, which includes class definitions and inheritance. The concept of interface and interface implementation is absent. Hence, when inheriting a function, it is the job of the programmer to make sure a method is overloaded correctly (otherwise it is just another definition of the class).

Below, we illustrate some examples of Python's object-oriented idiom:

class Example:
   # the class constructor.
   def __init___(self,param1,param2):
      # the keyword self is similar to this from Java
      # it is the only legal mode of initialising and referring class member variables
      self.member1 = param1  
      # here member2 is a local variable, which is not visible outside of the constructor
      member2 = param2
 
   def fun(self):
      # a member function must always refer self as shown here. Otherwise it is just a function
      # defined in the scope of the class, not a member function.
      return 0
 
   def plus(self,x,y):
      return x + y
 
   # this is the equivalent of Java's toString method
   def __str__(self):
      string = ...
      return string
 
#global scope
 
#class instantiation
e = Example(1,2) 
 
#method calls:
e.fun()
 
print(e)

2.1.1 Define the class Dfa which encodes deterministic finite automata. It must store:

  • the alphabet
  • the delta function
  • the initial state
  • the set of final states

Optional: you may consider defining a class State to encode more general Dfas where states are not confined to integers. This will be useful later in your project. However, you will need to define a hash-function in order to use dictionaries over states. More details, google hashing in Python.

2.1.2. Define a constructor for Dfas, which takes a multi-line string of the following form:

<initial_state>
<state> <char> <state>
...
...
<final_state_1> <final_state_2> ... <final_state_n>

where:

  1. the initial state is given on the first line of the input
  2. each of the subsequent lines encode transitions (states are integers)
  3. the last line encodes the set of final states.

Example:

0
0 a 1
1 b 2
2 a 0
1 2

2.1.3. Implement a member function which takes a configuration (pair of state and rest of word) and returns the next configuration.

2.1.4. Implement a member function which verifies if a word is accepted by a Dfa.

Write Dfas and test them using your implementation, for the following languages:

  • 2.2.2. $ L=\{w \in \{0,1\}^* \text{ | w contains an odd number of 1s} \} $
  • 2.2.3. The language of binary words which contain exactly two ones
  • 2.2.4. The language of binary words which encode odd numbers (the last digit is least significative)
  • 2.2.5. (hard) The language of words which encode numbers divisible by 3.