|
| 1 | +""" |
| 2 | +ARITHMETIC MEAN : https://en.wikipedia.org/wiki/Arithmetic_mean |
| 3 | +
|
| 4 | +""" |
| 5 | + |
| 6 | + |
| 7 | +def is_arithmetic_series(series: list) -> bool: |
| 8 | + """ |
| 9 | + checking whether the input series is arithmetic series or not |
| 10 | +
|
| 11 | + >>> is_arithmetic_series([2, 4, 6]) |
| 12 | + True |
| 13 | + >>> is_arithmetic_series([3, 6, 12, 24]) |
| 14 | + False |
| 15 | + >>> is_arithmetic_series([1, 2, 3]) |
| 16 | + True |
| 17 | + """ |
| 18 | + if len(series) == 1: |
| 19 | + return True |
| 20 | + common_diff = series[1] - series[0] |
| 21 | + for index in range(len(series) - 1): |
| 22 | + if series[index + 1] - series[index] != common_diff: |
| 23 | + return False |
| 24 | + return True |
| 25 | + |
| 26 | + |
| 27 | +def arithmetic_mean(series: list) -> float: |
| 28 | + """ |
| 29 | + return the arithmetic mean of series |
| 30 | +
|
| 31 | + >>> arithmetic_mean([2, 4, 6]) |
| 32 | + 4.0 |
| 33 | + >>> arithmetic_mean([3, 6, 9, 12]) |
| 34 | + 7.5 |
| 35 | + >>> arithmetic_mean(4) |
| 36 | + Traceback (most recent call last): |
| 37 | + ... |
| 38 | + ValueError: Input series is not valid, valid series - [2, 4, 6] |
| 39 | + >>> arithmetic_mean([4, 8, 1]) |
| 40 | + Traceback (most recent call last): |
| 41 | + ... |
| 42 | + ValueError: Input list is not an arithmetic series |
| 43 | + >>> arithmetic_mean([1, 2, 3]) |
| 44 | + 2.0 |
| 45 | + >>> arithmetic_mean([]) |
| 46 | + Traceback (most recent call last): |
| 47 | + ... |
| 48 | + ValueError: Input list must be a non empty list |
| 49 | +
|
| 50 | + """ |
| 51 | + if not isinstance(series, list): |
| 52 | + raise ValueError("Input series is not valid, valid series - [2, 4, 6]") |
| 53 | + if len(series) == 0: |
| 54 | + raise ValueError("Input list must be a non empty list") |
| 55 | + if not is_arithmetic_series(series): |
| 56 | + raise ValueError("Input list is not an arithmetic series") |
| 57 | + answer = 0 |
| 58 | + for val in series: |
| 59 | + answer += val |
| 60 | + return answer / len(series) |
| 61 | + |
| 62 | + |
| 63 | +if __name__ == "__main__": |
| 64 | + import doctest |
| 65 | + |
| 66 | + doctest.testmod() |
0 commit comments