Advertisement
danielperezunlpam

LL1 Parser

Sep 30th, 2019 (edited)
714
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.40 KB | None | 0 0
  1. class Parser(object):
  2.     """
  3.    Parser LL1
  4.        Gramática original:
  5.            S -> 0S1
  6.            S -> 01
  7.  
  8.        Gramática LL1:
  9.            S -> 0T
  10.            T -> S1
  11.            T -> 1
  12.    """
  13.  
  14.     def __init__(self):
  15.         self.cadena = None
  16.  
  17.     def evaluate(self, cadena):
  18.         """
  19.        Evalúa la cadena
  20.        :param cadena:
  21.        :return True | False:
  22.        """
  23.         self.cadena = cadena
  24.         self.S()
  25.         return self.cadena[0] == "$"
  26.  
  27.     def S(self):
  28.         print("S", self.cadena)
  29.         if self.cadena[0] == "0":
  30.             self.match("0")
  31.             self.T()
  32.         else:
  33.             raise Exception("Error", "En S")
  34.  
  35.     def T(self):
  36.         print("T", self.cadena)
  37.         if self.cadena[0] == "0":
  38.             self.S()
  39.             self.match("1")
  40.         elif self.cadena[0] == "1":
  41.             self.match("1")
  42.         else:
  43.             raise Exception("Error", "En T")
  44.  
  45.     def match(self, s):
  46.         print("M", self.cadena, s)
  47.         if s == self.cadena[0]:
  48.             self.cadena = self.cadena[1:]
  49.         else:
  50.             raise Exception("Error", "En Match")
  51.  
  52.  
  53. if __name__ == '__main__':
  54.     p = Parser()
  55.     word = "0011$"
  56.     print(f"S('{word}') -> {p.evaluate(word)}")
  57.     word = "00111$"
  58.     print(f"S('{word}') -> {p.evaluate(word)}")
  59.     word = "001011$"
  60.     print(f"S('{word}') -> {p.evaluate(word)}")
  61.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement