automate.py

Created by pascal-chauvin

Created on April 19, 2020

1.42 KB

Automate reconnaissant ou non un mot.


# fichier : automate.py
#  auteur : Pascal CHAUVIN
#    date : 2020/04/19

class Automate(object):

  def __init__(self, nombre_etats):
    self.__transitions = [{} for i in range(nombre_etats)]
    self.__acceptes = [False] * nombre_etats

  def arc(self, source, etiquette, cible):
    self.__transitions[source][etiquette] = cible

  def etat_final(self, etat):
    self.__acceptes[etat] = True

  def reconnaitre(self, mot):
    erreur = False

    etat = 0 # etat initial
    for etiquette in mot:
      if etiquette in self.__transitions[etat]:
        etat = self.__transitions[etat][etiquette]
      else:
        erreur = True

    if erreur:
      return False
    else:
      return self.__acceptes[etat]

def exemple():

  a = Automate(4)

  a.arc(0, 'a', 0)
  a.arc(0, 'd', 1)
  a.arc(1, 'a', 1)
  a.arc(1, 'e', 1)
  a.arc(1, 'b', 2)
  a.arc(2, 'c', 1)
  a.arc(2, 'i', 2)
  a.arc(2, 'f', 3)

  a.etat_final(3)

  print(a.reconnaitre('albert')) # .......... False
  print(a.reconnaitre('adecif')) # .......... False
  print(a.reconnaitre('adebif')) # .......... True
  print(a.reconnaitre('debif')) # ........... True
  print(a.reconnaitre('aaaadaaeebiif')) # ... True
  print(a.reconnaitre('daa')) # ............. False

  print("choisir un mot (ou vide) :")

  fini = False
  while not fini:
    s = str(input(">>>"))
    fini = (len(s) == 0)
    if not fini:
      print(a.reconnaitre(s))
  print("fin")
  
exemple()

During your visit to our site, NumWorks needs to install "cookies" or use other technologies to collect data about you in order to:

With the exception of Cookies essential to the operation of the site, NumWorks leaves you the choice: you can accept Cookies for audience measurement by clicking on the "Accept and continue" button, or refuse these Cookies by clicking on the "Continue without accepting" button or by continuing your browsing. You can update your choice at any time by clicking on the link "Manage my cookies" at the bottom of the page. For more information, please consult our cookies policy.