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)
 
 

[Deprecated] Deterministic finite automata

1. Writing DFAs

1.1. Write a DFA which accepts the language $ L=\{w \in \{0,1\}^* \text{ | w contains an odd number of 1s} \} $ Hint:

  • in a DFA, delta is total!

1.2 Define a DFA which accepts arithmetic expressions. Consider the following definition for arithmetic expressions:

​
<expr> ::= <var> | <expr> + <expr> | <expr> * <expr>
<var> ::= a | b

Hint:

  • how would you define the alphabet for the DFA?
  • can <expr> be the empty string?

2. Implementing DFAs

Consider the following encoding of a DFA:

   <number_of_states>
   <list_of_final_states>
   <state> <symbol> <state>

Example:

4
2 3
0 a 1
1 b 2
2 a 0

2.1. Write a function which takes a DFA encoding as above and returns a DFA representation. Define a class “DFA”.

2.2. Add a method accept which takes a word and returns true if it is accepted by the DFA

2.3. Add a method step with takes a DFA configuration and returns the “next-step” configuration of the DFA. How is a configuration defined?

2.4(*) Write a method which:

  • takes a list of DFAs $ a_1, a_2, \ldots, a_n$
  • takes a string $ s$. We know the string consists of a sequence of words, each accepted by some dfa in the list.
  • returns a list of pairs $ (w_1,a_1), \ldots(w_i,a_i) \ldots (w_n,a_n)$ such that $ w_1w_2\ldots w_n = s$ and the dfa $ a_i$ accepts word $ w_i$, for each i from 1 to n.

Example:

l = [a1, a2, a3]
 ''' 
    a1 accepts sequences of digits [0-9]
    a2 accepts sequences of lowercase symbols [a-z]
    a3 accepts operands (+ and *)
 '''
s = "var+40*2300"

our function returns:
[("var",2), ("+",3), ("40",1), ("*",3), ("2300",1)]