Ported Lahiru's tokneizer code over. Appears to work fine. Also did some house keeping.
This commit is contained in:
@@ -1,47 +1,8 @@
|
||||
import token
|
||||
import tokenizer
|
||||
#userInput = input('Enter your formula: ')
|
||||
tokens = tokenizer.get_tokens_from_expression_string("1 + 2 / 3 (3 * 4) 5")
|
||||
|
||||
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.")
|
||||
for t in tokens:
|
||||
print("%s (%s) " %(t.value, token.TokenType.get_operator_name(t.type)), end = "")
|
||||
print()
|
||||
|
||||
Reference in New Issue
Block a user