The calculator supports the basic operators (Add,Substract,Divide,Multiply).
At the moment,
- It only works with positive integers
- I do not validate my user input
- My division rounds up if it isn't an integer
This is a work in progress. It is my first Python application so I want to get feedback before I keep on working on it.
Here is an example of how my calculator parses/processes an equation :
Given 3+3+9/3-4*2
Computing multiplications : 3+3+9/3-8 (Note that 4*2 is now 8)
Then divisions : 3+3+3-8 (9/3 = 3)
Then additions : 9-8 (3+3+3 = 9)
Finally substractions : 1 (9-8 = 1)
import operator
priorizedOperators = operator.getPriorizedOperators()
def calculate(args):
return _calculate(args,0)
def _calculate(equation, operatorArrayIndex):
if len(priorizedOperators) == operatorArrayIndex:
return equation;
arithmeticOperator = priorizedOperators[operatorArrayIndex]
copiedEquation = equation
try:
operatorLocation = copiedEquation.index(arithmeticOperator.getStringSign())
while True:
leftBound = _findLeftBound(equation,operatorLocation)
rightBound = _findRightBound(equation,operatorLocation)
leftValue = int(copiedEquation[leftBound:operatorLocation])
rightValue = int(copiedEquation[operatorLocation+1:rightBound])
temp = arithmeticOperator.operate(leftValue,rightValue)
#Replaces the part of the equation we just computed by the result
copiedEquation = copiedEquation[:leftBound] + str(temp) + copiedEquation[rightBound:]
#This will throw an exception if index doesn't find the operator, which ends the while loop
operatorLocation = copiedEquation.index(arithmeticOperator.getStringSign())
finally:
return _calculate(copiedEquation, operatorArrayIndex + 1)
def _findLeftBound(equation ,operatorIndex):
for leftBoundSearchIndex in reversed(range(0,operatorIndex)):
if not _isNumber(equation[leftBoundSearchIndex]):
return leftBoundSearchIndex + 1
return 0
def _findRightBound(equation, operatorIndex):
for rightBoundSearchIndex in range(operatorIndex+1, len(equation)):
if not _isNumber(equation[rightBoundSearchIndex]):
return rightBoundSearchIndex
return len(equation)
def _isNumber(char):
return ord("0") <= ord(char) <= ord("9")
def main():
equation = input("Enter equation : ")
print(calculate(equation))
if __name__ == "__main__": main()
Content of the operator.py
class PlusOperator():
def getStringSign(self):
return "+"
def operate(self,left,right):
return left + right
class MinusOperator():
def getStringSign(self):
return "-"
def operate(self,left,right):
return left - right
class MultiplyOperator():
def getStringSign(self):
return "*"
def operate(self,left,right):
return left * right
class DivideOperator():
def getStringSign(self):
return "/"
def operate(self,left,right):
return left // right
def getPriorizedOperators():
return [MultiplyOperator(),DivideOperator(),PlusOperator(),MinusOperator()]
I'm looking to know if my python is okay and if my algorithm makes sense.