Skip to content
Browse files

line-oriented calculator

  • Loading branch information...
1 parent a7b40c5 commit 77cf941e02fef62a7878308302b50b192330a9d1 Matthew Hooker committed Nov 4, 2011
Showing with 38 additions and 0 deletions.
  1. +38 −0 bin/lcalc.py
View
38 bin/lcalc.py
@@ -0,0 +1,38 @@
+#!/usr/bin/env python
+"""
+lcalc.py is a line oriented calculator
+
+Usage:
+ lcalc.py <+-/*> < input
+"""
+
+from __future__ import division
+import argparse
+import sys
+
+parser = argparse.ArgumentParser()
+parser.add_argument('operator', nargs=1, choices=['+', '-', '*', '/'],
+ help='Operator for input.')
+
+args = parser.parse_args()
+
+operator_map = {
+ '+': lambda lhs, rhs: lhs + rhs,
+ '-': lambda lhs, rhs: lhs - rhs,
+ '*': lambda lhs, rhs: lhs * rhs,
+ '/': lambda lhs, rhs: lhs / rhs
+}
+
+def num(s):
+ try:
+ return int(s)
+ except ValueError:
+ return float(s)
+
+try:
+ operands = [num(line.strip()) for line in sys.stdin]
+except ValueError, e:
+ sys.stderr.write("Problem parsing input. %s\n" % e)
+ sys.exit(-1)
+
+print reduce(operator_map[args.operator[0]], operands)

0 comments on commit 77cf941

Please sign in to comment.
Something went wrong with that request. Please try again.