Design Pattern Examples
Overview of object-oriented design patterns
interpreter_class.py
Go to the documentation of this file.
6
7from io import StringIO
8
9
10
26
27 PERIOD = 100
28
29 QUESTION = 101
30
31
33 _commonwords = [
34 "the",
35 "be",
36 "to",
37 "of",
38 "and",
39 "a",
40 "in",
41 "that",
42 "have",
43 "I",
44 "it",
45 "for",
46 "not",
47 "on",
48 "with",
49 "he",
50 "as",
51 "you",
52 "do",
53 "at",
54 "this",
55 "but",
56 "his",
57 "by",
58 "from",
59 "they",
60 "we",
61 "say",
62 "her",
63 "she",
64 "or",
65 "an",
66 "will",
67 "my",
68 "one",
69 "all",
70 "would",
71 "there",
72 "their",
73 "what",
74 ]
75
76
77
86 def _InterpretToken(self, token : int) -> str:
87 tokenAsString = ""
88
89 # Rule 1: token is between 0 and the number of common words.
90 if token >= 0 and token < len(Interpreter_Class._commonwords):
91 tokenAsString = Interpreter_Class._commonwords[token]
92 else:
93 # Rule 1: token can also be a PERIOD
94 if token == Interpreter_Class.PERIOD:
95 tokenAsString = "."
96 # Rule 1: or the token can also be a QUESTION
97 elif token == Interpreter_Class.QUESTION:
98 tokenAsString = "?"
99 else:
100 # Rule 1: Invalid tokens returned in a string.
101 tokenAsString = "<UNKNOWN TOKEN {0}>".format(token)
102
103 return tokenAsString;
104
105
106
113 def Interpret(self, tokens : list[int]) -> str:
114 output = StringIO()
115
116 numTokens = len(tokens)
117
118 for tokenIndex in range(0, numTokens):
119 # Rule 1: Interpret token
120 tokenAsString = self._InterpretToken(tokens[tokenIndex])
121 if tokenIndex == 0:
122 # Rule 2: First word in sentence gets capitalized according to local rules.
123 tokenAsString = tokenAsString.title()
124 output.write(tokenAsString)
125
126 # Rule 4: No space between last two tokens (if the following expression is false)
127 if tokenIndex + 2 < numTokens:
128 # Rule 3: Separate all words by a single space.
129 output.write(" ")
130
131 return output.getvalue()
str Interpret(self, list[int] tokens)
Given an array of integer tokens, convert the tokens into a single string of space-delimited words,...
str _InterpretToken(self, int token)
Helper method to convert the token into its corresponding word or punctuation mark.