forked from greneus/average_squares
-
Notifications
You must be signed in to change notification settings - Fork 0
/
squares.py
70 lines (57 loc) · 2.28 KB
/
squares.py
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
"""Computation of weighted average of squares."""
from argparse import ArgumentParser
def average_of_squares(list_of_numbers, list_of_weights=None):
""" Return the weighted average of a list of values.
By default, all values are equally weighted, but this can be changed
by the list_of_weights argument.
Example:
--------
>>> average_of_squares([1, 2, 4])
7.0
>>> average_of_squares([2, 4], [1, 0.5])
8.0
>>> average_of_squares([1, 2, 4], [1, 0.5])
Traceback (most recent call last):
AssertionError: weights and numbers must have same length
"""
if list_of_weights is not None:
assert len(list_of_weights) == len(list_of_numbers), \
"weights and numbers must have same length"
effective_weights = list_of_weights
else:
effective_weights = [1] * len(list_of_numbers)
squares = [
weight * number * number
for number, weight
in zip(list_of_numbers, effective_weights)
]
return sum(squares)/sum(effective_weights)
def convert_numbers(list_of_strings):
"""Convert a list of strings into numbers, ignoring whitespace.
Example:
--------
>>> convert_numbers(["4", " 8 ", "15 16", " 23 42 "])
[4.0, 8.0, 15.0, 16.0, 23.0, 42.0]
"""
all_numbers = []
for s in list_of_strings:
# Take each string in the list, split it into substrings separated by
# whitespace, and collect them into a single list...
all_numbers.extend([token.strip() for token in s.split()])
# ...then convert each substring into a number
return [float(number_string) for number_string in all_numbers]
if __name__ == "__main__":
numbers_strings = ["1","2","4"]
weight_strings = ["1","1","1"]
parser = ArgumentParser(description='Input list of numbers to average over')
parser.add_argument('number_list', nargs="*", type=str)
#numbers = convert_numbers(numbers_strings)
arguments = parser.parse_args()
print(arguments)
numbers = convert_numbers(arguments.number_list)
assert (len(numbers) == len(weights))
#assert (type(numbers) == float).all()
print('terminal input: ', numbers)
weights = convert_numbers(weight_strings)
result = average_of_squares(numbers, weights)
print(result)