SeesSound
SeesSound

Reputation: 505

Python: Dealing with a second operator in calculator

I am creating a calculator program and I am nearly complete. The last problem I am encountering is dealing with a second operator.

The program takes an expression with a maximum of two operators(ex.2/3*4). It splits it into 2,/,3,*,4 and the uses many varying functions to solve the expression. Now the specific part I am presenting below is the function that solves the first expression, (I have solved the rest of it already):

def firstOperationWithOneOperator(numEx1,numEx2,opEx1):

    if opEx1=="*":
        solution1=numEx1*numEx2
        print(solution1)
        return solution1
    elif opEx1=="/":
        solution1=numEx1/numEx2
        print(solution1)
        return solution1
    elif opEx1=="+":
        solution1=numEx1+numEx2
        print(solution1)
        return solution1
    elif opEx1=="-":
        solution1=numEx1-numEx2
        print(solution1)
        return solution1

So I now have a working function to solve something with one operator(ex.2/3) as you can see above. I needed some help finding out how to deal with a second operator while keeping the order of operations in check. So how can I solve an expression such as 2+3*5? I will keep updating my OP with limitations as they are presented, if any. If anything is unclear please ask and I will edit the OP.

EDIT:

def fowoo(nums1,fowoo(nums2,nums3,ops2),ops1):
    print(fOWOO(nums1, fOWOO(nums2, nums3, ops2), ops1))

Upvotes: 0

Views: 281

Answers (1)

Eric
Eric

Reputation: 97591

fOWOO = firstOperationWithOneOperator

You need to decide between:

fOWOO(num1, fOWOO(num2, num3, op2), op1)  # num1 `op1` (num2 `op2` num3)

and

fOWOO(fOWOO(num1, num2, op1), num3, op2)  # (num1 `op1` num2) `op2` num3

Based on the precedence of op1 and op2


So:

  • 2 / 3 + 4 -> fOWOO(fOWOO(2, 3, '/'), 4, '+')
  • 2 + 3 / 4 -> fOWOO(2, fOWOO(3, 4, '/'), '+')

Upvotes: 1

Related Questions