2021-04-16 18:23:28 +02:00
|
|
|
#!/usr/bin/env python3
|
|
|
|
|
|
|
|
import sys
|
|
|
|
import operator
|
|
|
|
from functools import reduce as fold
|
|
|
|
import argparse
|
|
|
|
|
|
|
|
|
2021-04-16 18:25:56 +02:00
|
|
|
product = lambda xs: fold(operator.mul, xs)
|
2021-04-16 18:23:28 +02:00
|
|
|
operators = {
|
|
|
|
"sum": sum, "+": sum,
|
2021-04-16 18:25:56 +02:00
|
|
|
"mul": product, "product": product, "prod": product, "*": product,
|
2021-04-16 18:23:28 +02:00
|
|
|
"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))
|