Search code examples
pythondjangoautomaton

Django - Modeling a transition function


I'm using Django and trying to create a model for a Finite automaton and this is what I came up with so far:

class Alphabet(models.Model):
    alphabet = models.CharField(max_length = 10, null = True, blank = True)
    automata = models.ForeignKey(Automata, on_delete = models.CASCADE)

class States(models.Model):
    state = models.CharField(max_length = 10, null = True, blank = True)
    final = models.BooleanField(default = False)
    initial = models.BooleanField(default = False)
    automata = models.ForeignKey(Automata, on_delete = models.CASCADE)

class Automata(models.Model):
    pass

Now I would like to model the transition function, there is one for each automaton:

Example: we can go from state1 to state2 using symbol1

I'm not sure how to go through with that, any help would be appreciated!


Solution

  • The following could model a single transition of the transition function for a finite automaton. It is worth noting, however, that deterministic finite automata and non-deterministic finite automata transitions look different. DFA transitions map to a single state, whereas NFA transitions map to a set of states. You will have to bear this in mind when adding the relations.

    class Transition(models.Model):
    
        current_state = models.ForeignKey(State)
        symbol = models.CharField(max_length=1)
        next_state = models.ForeignKey(State)
    
        def __str__(self):
            return "T({0}, {1}) = {2}".format(
                self.current_state,
                self.symbol,
                self.next_state
            )