This repository has been archived by the owner on Aug 7, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathaverage
executable file
·58 lines (51 loc) · 1.54 KB
/
average
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#!/usr/bin/python3
import argparse
import sys
from sys import stdin, stdout, stderr
import re
import statistics
def avg_per_line():
try:
data = [i.replace("\n","").split(" ") for i in stdin]
average = []
for i in data:
try:
data = [int(j) for j in i]
except ValueError:
data = [float(j) for j in i]
average.append(statistics.mean(data))
return average
except ValueError as e:
stderr.write(f"Invalid input value: {e}\nTry: {sys.argv[0]} --help\n")
exit(1)
def avg_total():
try:
data = "".join([i for i in stdin])
data = re.split('[,\n\s]', data)
data = list(filter(None, data))
try:
data = [int(i) for i in data]
except ValueError:
data = [float(i) for i in data]
return statistics.mean(data)
except ValueError as e:
stderr.write(f"Invalid input value: {e}\nTry: {sys.argv[0]} --help\n")
exit(1)
def main():
parser = argparse.ArgumentParser(
description="Get the average of the numbers on the line.")
parser.add_argument('-a','--all',
help="Compute the average from all numbers, not the average per line.",
action="store_true")
args = parser.parse_args()
if args.all:
data = avg_total()
else:
data = avg_per_line()
try:
for i in data:
stdout.write(f"{i}\n")
except TypeError:
stdout.write(f"{data}\n")
if __name__ == "__main__":
main()