Skip to content

Commit 868c2fa

Browse files
authored
Rewrite fibonacci.py (#5665) (#5677)
* Removed doctest call * Removed 0 and 1 append to `fib_array` * Moved fibonacci sequence logic into `calculate` * Refactored `get` to generate missing numbers * Renamed `fib_array` to `sequence` * Renamed `number` to `index` * Refactored `get` to only return sequence to `index` * Moved main block into function * Added documentation to `get` * Added missing type hints * Fixed doctest error in `get` docstring * Moved calculate logic into get * Reformatted with black * Fixed wrong generation range
1 parent a64c9f1 commit 868c2fa

File tree

1 file changed

+38
-51
lines changed

1 file changed

+38
-51
lines changed

dynamic_programming/fibonacci.py

+38-51
Original file line numberDiff line numberDiff line change
@@ -5,61 +5,48 @@
55

66

77
class Fibonacci:
8-
def __init__(self, N=None):
9-
self.fib_array = []
10-
if N:
11-
N = int(N)
12-
self.fib_array.append(0)
13-
self.fib_array.append(1)
14-
for i in range(2, N + 1):
15-
self.fib_array.append(self.fib_array[i - 1] + self.fib_array[i - 2])
16-
elif N == 0:
17-
self.fib_array.append(0)
18-
print(self.fib_array)
8+
def __init__(self) -> None:
9+
self.sequence = [0, 1]
1910

20-
def get(self, sequence_no=None):
11+
def get(self, index: int) -> list:
2112
"""
22-
>>> Fibonacci(5).get(3)
23-
[0, 1, 1, 2, 3, 5]
24-
[0, 1, 1, 2]
25-
>>> Fibonacci(5).get(6)
26-
[0, 1, 1, 2, 3, 5]
27-
Out of bound.
28-
>>> Fibonacci(5).get(-1)
29-
[0, 1, 1, 2, 3, 5]
30-
[]
13+
Get the Fibonacci number of `index`. If the number does not exist,
14+
calculate all missing numbers leading up to the number of `index`.
15+
16+
>>> Fibonacci().get(10)
17+
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
18+
>>> Fibonacci().get(5)
19+
[0, 1, 1, 2, 3]
3120
"""
32-
if sequence_no is not None:
33-
if sequence_no < len(self.fib_array):
34-
return print(self.fib_array[: sequence_no + 1])
35-
else:
36-
print("Out of bound.")
37-
else:
38-
print("Please specify a value")
21+
difference = index - (len(self.sequence) - 2)
22+
if difference >= 1:
23+
for _ in range(difference):
24+
self.sequence.append(self.sequence[-1] + self.sequence[-2])
25+
return self.sequence[:index]
3926

4027

41-
if __name__ == "__main__":
42-
print("\n********* Fibonacci Series Using Dynamic Programming ************\n")
43-
print("\n Enter the upper limit for the fibonacci sequence: ", end="")
44-
try:
45-
N = int(input().strip())
46-
fib = Fibonacci(N)
47-
print(
48-
"\n********* Enter different values to get the corresponding fibonacci "
49-
"sequence, enter any negative number to exit. ************\n"
50-
)
51-
while True:
52-
try:
53-
i = int(input("Enter value: ").strip())
54-
if i < 0:
55-
print("\n********* Good Bye!! ************\n")
56-
break
57-
fib.get(i)
58-
except NameError:
59-
print("\nInvalid input, please try again.")
60-
except NameError:
61-
print("\n********* Invalid input, good bye!! ************\n")
28+
def main():
29+
print(
30+
"Fibonacci Series Using Dynamic Programming\n",
31+
"Enter the index of the Fibonacci number you want to calculate ",
32+
"in the prompt below. (To exit enter exit or Ctrl-C)\n",
33+
sep="",
34+
)
35+
fibonacci = Fibonacci()
36+
37+
while True:
38+
prompt: str = input(">> ")
39+
if prompt in {"exit", "quit"}:
40+
break
6241

63-
import doctest
42+
try:
43+
index: int = int(prompt)
44+
except ValueError:
45+
print("Enter a number or 'exit'")
46+
continue
6447

65-
doctest.testmod()
48+
print(fibonacci.get(index))
49+
50+
51+
if __name__ == "__main__":
52+
main()

0 commit comments

Comments
 (0)