-
-
Notifications
You must be signed in to change notification settings - Fork 46.6k
/
Copy pathgeometric_series.py
67 lines (59 loc) · 1.91 KB
/
geometric_series.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
"""
This is a pure Python implementation of the Geometric Series algorithm
https://en.wikipedia.org/wiki/Geometric_series
Run the doctests with the following command:
python3 -m doctest -v geometric_series.py
or
python -m doctest -v geometric_series.py
For manual testing run:
python3 geometric_series.py
"""
from typing import Union
def geometric_series(
nth_term: Union[float, int],
start_term_a: Union[float, int],
common_ratio_r: Union[float, int],
) -> list[Union[float, int]]:
"""
Pure Python implementation of Geometric Series algorithm
:param nth_term: The last term (nth term of Geometric Series)
:param start_term_a : The first term of Geometric Series
:param common_ratio_r : The common ratio between all the terms
:return: The Geometric Series starting from first term a and multiple of common
ration with first term with increase in power till last term (nth term)
Examples:
>>> geometric_series(4, 2, 2)
[2, 4.0, 8.0, 16.0]
>>> geometric_series(4.0, 2.0, 2.0)
[2.0, 4.0, 8.0, 16.0]
>>> geometric_series(4.1, 2.1, 2.1)
[2.1, 4.41, 9.261000000000001, 19.448100000000004]
>>> geometric_series(4, 2, -2)
[2, -4.0, 8.0, -16.0]
>>> geometric_series(4, -2, 2)
[-2, -4.0, -8.0, -16.0]
>>> geometric_series(-4, 2, 2)
[]
>>> geometric_series(0, 100, 500)
[]
>>> geometric_series(1, 1, 1)
[1]
>>> geometric_series(0, 0, 0)
[]
"""
if not all((nth_term, start_term_a, common_ratio_r)):
return []
series: list[Union[float, int]] = []
power = 1
multiple = common_ratio_r
for _ in range(int(nth_term)):
if series == []:
series.append(start_term_a)
else:
power += 1
series.append(start_term_a * multiple)
multiple = pow(float(common_ratio_r), power)
return series
if __name__ == "__main__":
import doctest
doctest.testmod()