From d0e36ff2ce544bff210f2f1142e86ea66a4372f4 Mon Sep 17 00:00:00 2001 From: Garritt McCune Date: Mon, 9 Mar 2020 18:44:02 -0500 Subject: [PATCH] Inital commit. --- main.py | 47 +++++++++++++++++++++++++++++++++++++++++++++++ token.py | 46 ++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 93 insertions(+) create mode 100755 main.py create mode 100755 token.py diff --git a/main.py b/main.py new file mode 100755 index 0000000..a0a7a24 --- /dev/null +++ b/main.py @@ -0,0 +1,47 @@ +import token + +def flatten_input(input): + tokens = [] + tmp = "" + parsing_number = False + + for i in range(0, len(input)): + c = input[i] + if c == '.' or c.isdigit(): + if len(tokens) > 1: + lookBehind = tokens[len(tokens) - 1] + + if lookBehind == token.TokenType.exp_start: + tokens.append(token.Token("^", token.TokenType.power)) + if (i + 1) == len(input): + tokens.append(token.Token(tmp + c, token.TokenType.constant)) + + parsing_number = True + tmp = tmp + c + continue + + print(tokens) + +def operate(n1, n2, tokenType): + if tokenType == token.TokenType.add: + print("Adding %d and %d to get %d." %(n1, n2, n1 + n2)) + elif tokenType == token.TokenType.subtract: + print("Subtracting %d and %d to get %d." %(n1, n2, n1 - n2)) + elif tokenType == token.TokenType.multiply: + print("Multiplying %d and %d to get %d" %(n1, n2, n1 * n2)) + elif tokenType == token.TokenType.divide: + print("Dividing %d and %d to get %d" %(n1, n2, n1 / n2)) + elif tokenType == token.TokenType.power: + print("Raising %d to the power of %d to get %d" %(n1, n2, n1**n2)) + else: + raise ValueError(f"Invalid operator value.") + +#t1 = token.TokenType() +#t = token.Token("+", token.TokenType.add) +#print(t1.get_operator_verb(t.type)) +operate(10, 2, 4) +operate(10, 2, 0) +operate(10, 2, 1) +operate(10, 2, 2) +operate(10, 2, 3) +flatten_input("THis is 96.") diff --git a/token.py b/token.py new file mode 100755 index 0000000..5822fc0 --- /dev/null +++ b/token.py @@ -0,0 +1,46 @@ +class Token: + def __init__(self, value, type): + self.value = value + self.type = type + +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" + } + + OPERATORS = { + '+' : add, + '-' : subtract, + '*' : multiply, + '^' : power, + '/' : divide + } + + def get_operator_verb(self, token): + if not token in self.OPERATOR_VERBS: + raise ValueError("An operator verb could not be found.", "token") + return self.OPERATOR_VERBS[token] + + def get_operator(self, character): + if not character in self.OPERATORS: + raise ValueError(f"Invalid operator '{character}' could not be found in the operators list.", "character") + return self.OPERATORS[character] + +#t = TokenType() +#t1 = Token("$", TokenType.Unknown) +#print(t.GetOperator(t1.value))