Fixed a bug where addition would always be evaluated before subtraction when, in reality, they have the same precedence.

master
Aadhavan Srinivasan 1 year ago
parent a7bd4f6c6e
commit 87f5c49bbb

@ -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] = ''

Loading…
Cancel
Save