Refactored some code to try and make it more inline with best pratices. Renamed parser as it conflicted with a standard Python library.
This commit is contained in:
Executable
+71
@@ -0,0 +1,71 @@
|
||||
class Token:
|
||||
# Represents the single smallest unit that makes up an expression.
|
||||
|
||||
def __init__(self, value, type, is_negative_variable = False):
|
||||
self.value = value
|
||||
self.type = type
|
||||
self.is_negative_variable = is_negative_variable
|
||||
|
||||
def __str__(self):
|
||||
return "Value: %s" %(self.value)
|
||||
|
||||
class TokenType:
|
||||
add = 0
|
||||
subtract = 1
|
||||
multiply = 2
|
||||
divide = 3
|
||||
power = 4
|
||||
variable = 5
|
||||
constant = 6
|
||||
exp_start = 7
|
||||
exp_end = 8
|
||||
unknown = 9
|
||||
|
||||
OPERATOR_VERBS = {
|
||||
0 : "Adding",
|
||||
1 : "Subtracting",
|
||||
2 : "Multiplying",
|
||||
3 : "Dividing",
|
||||
4 : "Raising"
|
||||
}
|
||||
|
||||
TOKEN_NAMES = {
|
||||
0 : "Addition",
|
||||
1 : "Subtraction",
|
||||
2 : "Multiplication",
|
||||
3 : "Division",
|
||||
4 : "Power",
|
||||
5 : "Variable",
|
||||
6 : "Constant",
|
||||
7 : "Expression Start",
|
||||
8 : "Expression End",
|
||||
9 : "Unknown"
|
||||
}
|
||||
|
||||
OPERATORS = {
|
||||
'+' : add,
|
||||
'-' : subtract,
|
||||
'*' : multiply,
|
||||
'^' : power,
|
||||
'/' : divide
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
def get_operator_verb(token):
|
||||
# Returns the verb that corresponds to the supplied Token object's value field, or
|
||||
# throws an error if the Token object isn't a mathmatical operator.
|
||||
if not token in TokenType.OPERATOR_VERBS:
|
||||
raise ValueError("An operator verb could not be found.", "token")
|
||||
return TokenType.OPERATOR_VERBS[token]
|
||||
|
||||
@staticmethod
|
||||
def get_operator(character):
|
||||
# Accepts an individual character and returns either the mathmatical operator TokenType or unknown.
|
||||
if not character in TokenType.OPERATORS:
|
||||
return TokenType.unknown
|
||||
return TokenType.OPERATORS[character]
|
||||
|
||||
@staticmethod
|
||||
def get_token_type_name(tokenType):
|
||||
# Returns the token's full name based on the TokenType value.
|
||||
return TokenType.TOKEN_NAMES[tokenType]
|
||||
Reference in New Issue
Block a user