From 87f5c49bbb192874a81334bec3fcc140aed16077 Mon Sep 17 00:00:00 2001 From: Aadhavan Srinivasan Date: Mon, 27 Nov 2023 14:10:31 -0500 Subject: [PATCH] Fixed a bug where addition would always be evaluated before subtraction when, in reality, they have the same precedence. --- calculator.py | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/calculator.py b/calculator.py index 3b23c9f..aaa937e 100644 --- a/calculator.py +++ b/calculator.py @@ -90,14 +90,15 @@ def evaluate(subexpr): # Evaluate a tokenized expression, that contains no paran subexpr[index] = float(subexpr[index-1]) * float(subexpr[index+1]) subexpr[index-1] = '' subexpr[index+1] = '' - elif '+' in subexpr: - index = subexpr.index('+') - subexpr[index] = float(subexpr[index-1]) + float(subexpr[index+1]) - subexpr[index-1] = '' - subexpr[index+1] = '' - elif '-' in subexpr: - index = subexpr.index('-') - subexpr[index] = float(subexpr[index-1]) - float(subexpr[index+1]) + elif '+' in subexpr or '-' in subexpr: # Addition and subtraction have the same precedence + index_plus, index_minus = float('inf'), float('inf') # Set both values to infinity + if '+' in subexpr: + index_plus = subexpr.index('+') + if '-' in subexpr: + index_minus = subexpr.index('-') + + index = index_plus if index_plus < index_minus else index_minus # Set the index to the index of the operator that occurs first + subexpr[index] = float(subexpr[index-1]) + float(subexpr[index+1]) if index_plus < index_minus else float(subexpr[index-1]) - float(subexpr[index+1]) # If addition occured first, add the previous and next tokens. If subtraction occured first, subtract them. subexpr[index-1] = '' subexpr[index+1] = ''