forked from TheAlgorithms/Python
-
Notifications
You must be signed in to change notification settings - Fork 0
/
lucas_series.py
66 lines (58 loc) · 1.8 KB
/
lucas_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
"""
https://en.wikipedia.org/wiki/Lucas_number
"""
def recursive_lucas_number(n_th_number: int) -> int:
"""
Returns the nth lucas number
>>> recursive_lucas_number(1)
1
>>> recursive_lucas_number(20)
15127
>>> recursive_lucas_number(0)
2
>>> recursive_lucas_number(25)
167761
>>> recursive_lucas_number(-1.5)
Traceback (most recent call last):
...
TypeError: recursive_lucas_number accepts only integer arguments.
"""
if not isinstance(n_th_number, int):
raise TypeError("recursive_lucas_number accepts only integer arguments.")
if n_th_number == 0:
return 2
if n_th_number == 1:
return 1
return recursive_lucas_number(n_th_number - 1) + recursive_lucas_number(
n_th_number - 2
)
def dynamic_lucas_number(n_th_number: int) -> int:
"""
Returns the nth lucas number
>>> dynamic_lucas_number(1)
1
>>> dynamic_lucas_number(20)
15127
>>> dynamic_lucas_number(0)
2
>>> dynamic_lucas_number(25)
167761
>>> dynamic_lucas_number(-1.5)
Traceback (most recent call last):
...
TypeError: dynamic_lucas_number accepts only integer arguments.
"""
if not isinstance(n_th_number, int):
raise TypeError("dynamic_lucas_number accepts only integer arguments.")
a, b = 2, 1
for _ in range(n_th_number):
a, b = b, a + b
return a
if __name__ == "__main__":
from doctest import testmod
testmod()
n = int(input("Enter the number of terms in lucas series:\n").strip())
print("Using recursive function to calculate lucas series:")
print(" ".join(str(recursive_lucas_number(i)) for i in range(n)))
print("\nUsing dynamic function to calculate lucas series:")
print(" ".join(str(dynamic_lucas_number(i)) for i in range(n)))