Design Pattern Examples
Overview of object-oriented design patterns
interpreter_exercise.py
Go to the documentation of this file.
6
7from io import StringIO
8
9from .interpreter_class import Interpreter_Class
10
11
14_sentenceTokenLists = [
15 [ 39, 18, 17, 27, 2, 7, 101 ], # "What do you say to that?"
16 [ 32, 17, 1, 0, 34, 2, 1, 37, 101 ], # "Will you be the one to be there?"
17 [ 36, 17, 8, 5, 32, 2, 18, 7, 101 ], # "Would you have a will to do that?"
18 [ 11, 12, 17, 9, 36, 12, 1, 6, 20, 100 ], # "For not you I would not be in this."
19 [ 26, 27, 7, 21, 36, 17, 27, 10, 101 ], # "We say that but would you say it?"
20 [ 23, 28, 32, 26, 32, 18, 10, 100 ] # "By her will we will do it."
21]
22
23
29def _TokensToString(tokens : list[int]) -> str:
30 output = StringIO()
31
32 output.write("[");
33 for index in range(0, len(tokens)):
34 output.write("{0:3}".format(tokens[index]))
35 if index + 1 < len(tokens):
36 output.write(", ")
37 output.write("]")
38 return output.getvalue()
39
40
41
56
57# ! [Using Interpreter in Python]
59 print()
60 print("Interpreter Exercise")
61
62 interpreter = Interpreter_Class()
63
64 for sentenceIndex in range(0, len(_sentenceTokenLists)):
65 tokenList = _sentenceTokenLists[sentenceIndex]
66
67 tokensAsString = _TokensToString(tokenList)
68
69 sentence = interpreter.Interpret(tokenList)
70
71 # 50 is a magic number corresponding to the longest token list
72 # expressed as a string. Derived empirically. It makes the
73 # output easier to, er, interpret.
74 print(" {0:<50} ==> \"{1}\"".format(tokensAsString, sentence))
75
76 print(" Done.")
77# ! [Using Interpreter in Python]
def Interpreter_Exercise()
Example of using the Interpreter Pattern.
str _TokensToString(list[int] tokens)
Helper method to convert a list of tokens to a string representation.