Added comments in the code to provide a little bit more insight into what's happening.
This commit is contained in:
+15
-1
@@ -6,12 +6,18 @@ from collections import deque
|
||||
debug = False
|
||||
|
||||
def calculate_results(tokens):
|
||||
# Main entry into the calc_engine.
|
||||
# Returns the result of arthmetic as described by the token list.
|
||||
return process_tokens(convert_to_deque(tokens), True)
|
||||
|
||||
def process_tokens(tokens, top_level = False):
|
||||
pending_operations = []
|
||||
running_total = 0
|
||||
p_ops_ran = False
|
||||
# Flag that inidicates a high priority set of mathmatical operations have occurred.
|
||||
# High priority (mulitplation, division, power for instance) act as a pivot on which we can
|
||||
# determine whether or not lower priority operations can safely be performed without violating
|
||||
# the order of operations.
|
||||
p_ops_ran = False
|
||||
|
||||
while True:
|
||||
if not tokens:
|
||||
@@ -95,6 +101,9 @@ def process_tokens(tokens, top_level = False):
|
||||
return running_total
|
||||
#handle add/sub
|
||||
def handle_pending(tokens):
|
||||
# Effectively, this function handles adding and subtracting as all higher priority mathmatical operations
|
||||
# would have already been processed.
|
||||
# Returns the result of the addition or subtraction of the provided token list.
|
||||
running_total = 0
|
||||
previous_token = None
|
||||
|
||||
@@ -119,6 +128,8 @@ def handle_pending(tokens):
|
||||
return running_total
|
||||
|
||||
def convert_to_deque(tokens):
|
||||
# Converts a list into a Deque collection object.
|
||||
# Returns a Deque object with the contents of the supplied list or array.
|
||||
deq = deque()
|
||||
|
||||
for tk in tokens:
|
||||
@@ -128,6 +139,8 @@ def convert_to_deque(tokens):
|
||||
|
||||
|
||||
def operate(n1, n2, tokenType):
|
||||
# Utility function to handle dealing with the various mathmatical operations that the engine can process.
|
||||
# Returns the result of any one of five mathmatical operations, else throws an error for unrecognized operations.
|
||||
n1 = float(n1)
|
||||
n2 = float(n2)
|
||||
|
||||
@@ -150,6 +163,7 @@ def operate(n1, n2, tokenType):
|
||||
raise TypeError("Invalid operator value " + str(tokenType) + ".", tokenType)
|
||||
|
||||
def print_t(tokens):
|
||||
# Prints to standard out a flattened representation of a Deque object.
|
||||
tmp = copy.deepcopy(tokens)
|
||||
|
||||
while True:
|
||||
|
||||
Reference in New Issue
Block a user