Search code examples
pythoncalculatoroperationoperand

How to find the operand and the operation in a string


So I was trying to figure out how to detect the number of operands and operations in a mathematical expression

Ex: 1+2*9/2

I was trying to separate the operands and the operations into their own form using functions because we have to check how many operations must be done and in the correct order (PEDMAS) as well.

I've taken the equation and taken out all the spaces already, now i have to find the number of operands and operations in the equation and then later use return to find the answer of the given mathematical expression by the user.

Any tips?


Solution

  • If expression can be not so simple as your sample you can use RPN - reverse polish notation

    If your expression is pretty simple(only base ops and values less then 10) and you only need to count than you can use something like this i guess:

    ops = '+-*/'
    operationsCount= sum(expr.count(op) for op in ops)
    operandsCount = len(expr) - operationsCount
    

    Or you can use this:

    def get_cnt(expr):
        ops = '+-*/'
        res = [expr]
        for op in ops:
            tmp = []
            for x in expr:
                tmp.extend(x.split(op))
            res = tmp[:]        
        return len(res), sum(expr.count(op) for op in ops)
    

    Now you have number of operators and operands - and it is quite easily to split row correctly on ops/opd and to calculate expression.