![]() |
|
Challenge (1) CLI Calculator - Printable Version +- Sinisterly (https://sinister.li) +-- Forum: Coding (https://sinister.li/Forum-Coding) +--- Forum: Python (https://sinister.li/Forum-Python) +--- Thread: Challenge (1) CLI Calculator (/Thread-Challenge-1-CLI-Calculator) Pages:
1
2
|
RE: Challenge (1) CLI Calculator - m0dem - 12-16-2015 (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. RE: Challenge (1) CLI Calculator - emad.shaaban92 - 02-16-2016 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)RE: Challenge (1) CLI Calculator - m0dem - 02-17-2016 (02-16-2016, 06:27 PM)emad.shaaban92 Wrote: I like it!
|