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 #11
(12-16-2015, 03:56 PM)Nevermore Wrote: I just got bored in history, I'll take it seriously and finish it later.

Oh, that's no problem.
I really liked the way you did it btw.

Reply

RE: Challenge (1) CLI Calculator #12
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)

[+] 1 user Likes emad.shaaban92's post
Reply

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






Users browsing this thread: 1 Guest(s)