chevron_left chevron_right
Login Register invert_colors photo_library


Stay updated and chat with others! - Join the Discord!
Thread Rating:
  • 0 Vote(s) - 0 Average


Bronze Challenge (1) CLI Calculator filter_list
Author
Message
RE: Challenge (1) CLI Calculator #13
(02-16-2016, 06:27 PM)emad.shaaban92 Wrote:
Code:
import operator as op

ops={'+': op.add,'-': op.sub,'*': op.mul,'/': op.div,'^': op.pow,'%': op.mod}

def parse(equation) :
    operators = ["^", "*", "/", "%", "+", "-"]
    result = {}
    for op in operators[::-1] :
        if op in equation :
            result['operator'] = op
            result['operands'] = [
                parse(equation[:equation.find(op)]),
                parse(equation[equation.find(op)+1:])
            ]
            return result
    return equation.strip()




def evaluate(equation):
    parsed = parse(equation)
    def _eval(parsed_eq) :
        if type(parsed_eq) is str and parsed_eq.isdigit() :
            return int(parsed_eq)
        else :
            operator = parsed_eq['operator']
            operands = parsed_eq['operands']
            return ops[operator](_eval(operands[0]),  _eval(operands[1]))
    
    return _eval(parsed)
    

exp = '3 + 4 * 5'
print parse(exp)

print evaluate(exp)

I like it! Smile

Reply




Messages In This Thread
Challenge (1) CLI Calculator - by m0dem - 12-14-2015, 03:02 AM
RE: Challenge (1) CLI Calculator - by m0dem - 12-14-2015, 03:19 PM
RE: Challenge (1) CLI Calculator - by m0dem - 12-15-2015, 01:48 AM
RE: Challenge (1) CLI Calculator - by meow - 12-15-2015, 04:22 AM
RE: Challenge (1) CLI Calculator - by m0dem - 12-15-2015, 04:31 AM
RE: Challenge (1) CLI Calculator - by Nil - 12-15-2015, 08:55 AM
RE: Challenge (1) CLI Calculator - by m0dem - 12-15-2015, 02:53 PM
RE: Challenge (1) CLI Calculator - by Inori - 12-16-2015, 03:30 PM
RE: Challenge (1) CLI Calculator - by m0dem - 12-16-2015, 03:51 PM
RE: Challenge (1) CLI Calculator - by Inori - 12-16-2015, 03:56 PM
RE: Challenge (1) CLI Calculator - by m0dem - 12-16-2015, 03:59 PM
RE: Challenge (1) CLI Calculator - by m0dem - 02-17-2016, 04:18 AM



Users browsing this thread: 1 Guest(s)