Design Pattern Examples
Overview of object-oriented design patterns
DesignPatternExamples_python.interpreter.interpreter_exercise Namespace Reference

Functions

str _TokensToString (list[int] tokens)
 Helper method to convert a list of tokens to a string representation.
 
def Interpreter_Exercise ()
 Example of using the Interpreter Pattern.
 

Variables

list _sentenceTokenLists
 A list of predefined token lists.
 

Function Documentation

◆ _TokensToString()

str _TokensToString ( list[int]  tokens)
protected

Helper method to convert a list of tokens to a string representation.

Parameters
tokensArray of ints to work with.
Returns
A string representation of the token list.

Definition at line 29 of file interpreter_exercise.py.

Referenced by DesignPatternExamples_python.interpreter.interpreter_exercise.Interpreter_Exercise().

◆ Interpreter_Exercise()

def Interpreter_Exercise ( void  )

Example of using the Interpreter Pattern.

The interpreter is instantiated then fed a series of arrays containing integer tokens. Each token represents a single word or punctuation mark. The interpreter converts that array of tokens to an actual sentence by interpreting the meaning of the tokens.

This is a very simple interpreter that handles the first token in a special way and supports punctuation. It is an example of a linear interpreter where tokens can appear in any order (it's up to the creator of the token list to make sure the outcome makes any sense).

The output shows the token list followed by the sentence produced from the tokens.

Definition at line 58 of file interpreter_exercise.py.

References DesignPatternExamples_python.interpreter.interpreter_exercise._TokensToString().

Variable Documentation

◆ _sentenceTokenLists

list _sentenceTokenLists
protected
Initial value:
1= [
2 [ 39, 18, 17, 27, 2, 7, 101 ], # "What do you say to that?"
3 [ 32, 17, 1, 0, 34, 2, 1, 37, 101 ], # "Will you be the one to be there?"
4 [ 36, 17, 8, 5, 32, 2, 18, 7, 101 ], # "Would you have a will to do that?"
5 [ 11, 12, 17, 9, 36, 12, 1, 6, 20, 100 ], # "For not you I would not be in this."
6 [ 26, 27, 7, 21, 36, 17, 27, 10, 101 ], # "We say that but would you say it?"
7 [ 23, 28, 32, 26, 32, 18, 10, 100 ] # "By her will we will do it."
8]

A list of predefined token lists.

Each token list represents a single sentence constructed from the 40 most common words in the English language. I don't use all 40 words, though; that would be silly.

Definition at line 14 of file interpreter_exercise.py.