Updated syntax tree to support variables in the espression.
This commit is contained in:
@@ -7,6 +7,8 @@ def calculate_results(node):
|
||||
|
||||
if type(node) is parser.Num:
|
||||
return float(node.value)
|
||||
elif type(node) is parser.Variable:
|
||||
return node.value
|
||||
|
||||
left = calculate_results(node.left)
|
||||
right = calculate_results(node.right)
|
||||
|
||||
@@ -34,6 +34,7 @@ class Parser:
|
||||
def __init__(self, tokens):
|
||||
if len(tokens) == 0:
|
||||
raise ValueError("Token list can't be empty")
|
||||
self.variables = {}
|
||||
self.tokens = tokens
|
||||
self.current_token = None
|
||||
self.advance_current_token()
|
||||
@@ -51,6 +52,7 @@ class Parser:
|
||||
return node
|
||||
elif self.current_token.type == token.TokenType.variable:
|
||||
node = Variable(self.current_token)
|
||||
self.variables[self.current_token.value] = node
|
||||
self.advance_current_token()
|
||||
return node
|
||||
elif self.current_token.type == token.TokenType.exp_start:
|
||||
@@ -91,3 +93,26 @@ class Parser:
|
||||
|
||||
def generate_ast(self):
|
||||
return self.topLevel()
|
||||
|
||||
def update_variable(self, symbol, value):
|
||||
if symbol in self.variables:
|
||||
self.variables[symbol].value = float(value)
|
||||
else:
|
||||
raise ValueError("Variable value must be a number.", value)
|
||||
|
||||
def update_variables(self, variables):
|
||||
if len(variables) == 0:
|
||||
return
|
||||
|
||||
for symbol in variables:
|
||||
if symbol in self.variables:
|
||||
self.variables[symbol].value = float(variables[symbol])
|
||||
else:
|
||||
raise ValueError("Variable value must be a number.")
|
||||
|
||||
def get_variable_value_pairs(self):
|
||||
keys = {}
|
||||
|
||||
for symbol in self.variables:
|
||||
keys[symbol] = self.variables[symbol].value
|
||||
return keys
|
||||
|
||||
Reference in New Issue
Block a user