Initial commit

This commit is contained in:
Midgard 2021-04-16 18:23:28 +02:00
commit ddc6306d53
Signed by: midgard
GPG key ID: 511C112F1331BBB4

55
maths Executable file
View file

@ -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))