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
/
interval
executable file
·78 lines (67 loc) · 2.4 KB
/
interval
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
#!/usr/bin/python3
import argparse
import sys
from sys import stdin, stdout, stderr
import re
def get_data():
"""Puts data onto the list."""
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 data
except ValueError as e:
stderr.write(f"Invalid input value: {e}\nTry: {sys.argv[0]} --help\n")
exit(1)
def interval(data):
"""Returns a list of values describing the numeric change of number
against the preceding one. The first one is always 0.
Plus list of percent change rounded to two decimals places.
in: [1, 5, 12, 1, 3, 4, 5, 5, 9, 8, -1, -20]
out: [0, 4, 7, -11, 2, 1, 1, 0, 4, -1, -9, -19]
%: [0.0,400.0,140.0,-91.67,250.0,14.29,25.0,0.0,80.0,-11.11,-112.5]"""
first_num = None
interval_data = []
percent_data = []
for i in data:
try:
interval_data.append(i - first_num)
percent_data.append(round(((i - first_num) / first_num) * 100, 2))
except TypeError:
zero = int(0) if isinstance(i, int) else float(0)
interval_data.append(zero)
percent_data.append(zero)
first_num = i
return data, interval_data, percent_data
def verbose(data):
print(f"Numbers:\tInterval:\tPercent Change:")
for i, j, k in data:
stdout.write(f"{i}\t\t{j}\t\t{k}%\n")
def single_data(data):
for i in data:
stdout.write(f"{i}\n")
def main():
parser = argparse.ArgumentParser(
description="Interval will calculate and print the numeric interval \
between one numberand the next one in an input stream.")
parser.add_argument('-p',
'--percent',help="To get just percent change",
action="store_true")
parser.add_argument('-V',
'--verbose',
help="To get full overwiev of numbers with interval and percent change.",
action="store_true")
args = parser.parse_args()
data, interval_data, percent_data = interval(get_data())
if args.verbose:
verbose(list(zip(data ,interval_data, percent_data))) # list of tuples
elif args.percent:
single_data(percent_data)
else:
single_data(interval_data)
if __name__ == "__main__":
main()