Question

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?

Was it helpful?

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.

OTHER TIPS

If you're allowed to, I'd recommend checking out the ast module. It's designed to do stuff like this for you using Python's own parser.

For an actual application, you'd probably use a parser generator like Ply.

For a simple homework assignment like this, you're probably expected to handcode a parser. First tokenize it (str.split), find the parenthesis, and then use precedence to group the other operations.

import re
exp = 1+2*9/2
ops = re.findall(r'[\+\-*/]', exp)
print len(ops)

I don't know why you wanna find the number of operands I think

re.findall(r'[0-9]+|[\+\-*/()]', exp)

is better.

so I think the regular expression can help you

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top