forked from TheAlgorithms/Python
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgeometric.py
More file actions
Latest commit
83 lines (73 loc) · 2.26 KB
/
Copy pathgeometric.py
File metadata and controls
83 lines (73 loc) · 2.26 KB
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
78
79
80
81
82
83
"""
Geometric Mean
Reference : https://en.wikipedia.org/wiki/Geometric_mean
Geometric series
Reference: https://en.wikipedia.org/wiki/Geometric_series
"""
defis_geometric_series(series: list) ->bool:
"""
checking whether the input series is geometric series or not
>>> is_geometric_series([2, 4, 8])
True
>>> is_geometric_series([3, 6, 12, 24])
True
>>> is_geometric_series([1, 2, 3])
False
>>> is_geometric_series([0, 0, 3])
False
>>> is_geometric_series([])
Traceback (most recent call last):
...
ValueError: Input list must be a non empty list
>>> is_geometric_series(4)
Traceback (most recent call last):
...
ValueError: Input series is not valid, valid series - [2, 4, 8]
"""
ifnotisinstance(series, list):
raiseValueError("Input series is not valid, valid series - [2, 4, 8]")
iflen(series) ==0:
raiseValueError("Input list must be a non empty list")
iflen(series) ==1:
returnTrue
try:
common_ratio=series[1] /series[0]
forindexinrange(len(series) -1):
ifseries[index+1] /series[index] !=common_ratio:
returnFalse
exceptZeroDivisionError:
returnFalse
returnTrue
defgeometric_mean(series: list) ->float:
"""
return the geometric mean of series
>>> geometric_mean([2, 4, 8])
3.9999999999999996
>>> geometric_mean([3, 6, 12, 24])
8.48528137423857
>>> geometric_mean([4, 8, 16])
7.999999999999999
>>> geometric_mean(4)
Traceback (most recent call last):
...
ValueError: Input series is not valid, valid series - [2, 4, 8]
>>> geometric_mean([1, 2, 3])
1.8171205928321397
>>> geometric_mean([0, 2, 3])
0.0
>>> geometric_mean([])
Traceback (most recent call last):
...
ValueError: Input list must be a non empty list
"""
ifnotisinstance(series, list):
raiseValueError("Input series is not valid, valid series - [2, 4, 8]")
iflen(series) ==0:
raiseValueError("Input list must be a non empty list")
answer=1
forvalueinseries:
answer*=value
returnpow(answer, 1/len(series))
if__name__=="__main__":
importdoctest
doctest.testmod()