Skip to content

Commit

Permalink
Code and structure for week06 docs exercises
Browse files Browse the repository at this point in the history
  • Loading branch information
HChughtai committed Nov 10, 2020
1 parent 3bc7eb6 commit 9ed24ad
Showing 1 changed file with 62 additions and 0 deletions.
62 changes: 62 additions & 0 deletions week06/average-squares-example/average_squares/squares.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
"""Computation of weighted average of squares."""


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])
6.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)


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, 8, 15, 16]
"""
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"]

numbers = convert_numbers(numbers_strings)
weights = convert_numbers(weight_strings)

result = average_of_squares(numbers, weights)

print(result)

0 comments on commit 9ed24ad

Please sign in to comment.