A while back, I wrote a simple calculator in Ruby. A few minutes ago I ran into a similar question in Stackoverflow, and decided to implement the Python version:

def is_number(s): try: float(s) return True except ValueError: return False def calc(expr): if is_number(expr): return float(expr) arr = expr.split('+') if len(arr) > 1: return sum(map(calc, arr)) arr = expr.split('-') if len(arr) > 1: return reduce(lambda x,y: x-y, map(calc, arr)) arr = expr.split('*') if len(arr) > 1: return reduce(lambda x,y: x*y, map(calc, arr), 1) arr = expr.split('/') if len(arr) > 1: return reduce(lambda x,y: x/y, map(calc, arr)) print calc("3+4-2 *2/ 2") # 5

Nice, isnâ€™t it?

Advertisements