Skip to content

Instantly share code, notes, and snippets.

@matchaxnb
Created May 12, 2022 10:21
Show Gist options
  • Save matchaxnb/aff332011c81e747e8049046b1ba66bf to your computer and use it in GitHub Desktop.
Save matchaxnb/aff332011c81e747e8049046b1ba66bf to your computer and use it in GitHub Desktop.
Do arithmetic operations from command line shell script input - once and for all.
#!/usr/bin/env python
"""Usage: math [sum|mean|median|min|max]
Do these fucking maths once and for all from shell input.
"""
import sys
op = sys.argv[1]
da = [float(f) for f in sys.stdin.readlines()]
da.sort()
def sum_input(data):
res = 0
for line in data:
res += line
return res
def mean_input(data):
amount_data = len(data)
total = sum_input(data)
return total / amount_data
def median_input(data):
return data[int(len(data) / 2)]
def min_input(data):
return min(data)
def max_input(data):
return max(data)
def err_handler(data):
return "unknown op"
print(__doc__)
sys.exit(1)
op_map = {
'sum': sum_input,
'mean': mean_input,
'median': median_input,
'min': min_input,
'max': max_input,
}
wanted = op_map.get(op, err_handler)
print(wanted(da))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment