commit ddc6306d5327cb2f843748ab0f3f479a34a13c28 Author: Midgard Date: Fri Apr 16 18:23:28 2021 +0200 Initial commit diff --git a/maths b/maths new file mode 100755 index 0000000..74376bd --- /dev/null +++ b/maths @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 + +import sys +import operator +from functools import reduce as fold +import argparse + + +mul = lambda xs: fold(operator.mul, xs) +operators = { + "sum": sum, "+": sum, + "mul": mul, "*": mul, + "max": max, + "min": min +} +default_operator = "+" + + +parser = argparse.ArgumentParser(description="Do maths on stdin") +parser.add_argument( + "operator", + metavar="op", + nargs='?', + choices=list(operators.keys()), + default=default_operator, + help="Action to take (one of: {}; default: {})".format( + ", ".join(operators.keys()), + default_operator + ) +) +parser.add_argument( + "--int", + dest="datatype", + action="store_const", + const=(int, "integer"), + default=(float, "decimal number"), + help="use integers (default: float)" +) +args = parser.parse_args() + + +op = operators[args.operator] +parse_func, datatype_name = args.datatype + +data = [] +for i, line in enumerate(sys.stdin, start=1): + if line == "\n": + continue + try: + data.append(parse_func(line)) + except ValueError: + print("Line {} could not be interpreted as a {}: {:r}".format(i, datatype_name, line.rstrip("\n"))) + sys.exit(3) + +print(op(data))