Skip to content

improve fibonacchi examples [change in title] #1

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 31 additions & 14 deletions main.py
Original file line number Diff line number Diff line change
@@ -1,17 +1,3 @@
def nth_fibonacci(n):

# Base case: if n is 0 or 1, return n
if n <= 1:
return n

# Recursive case: sum of the two preceding Fibonacci numbers
return nth_fibonacci(n - 1) + nth_fibonacci(n - 2)

n = 5
result = nth_fibonacci(n)
print(result)


# Function to calculate the nth Fibonacci number using memoization
def nth_fibonacci_util(n, memo):

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

review comment

Expand Down Expand Up @@ -71,3 +57,34 @@ def nth_fibonacci(n):
n = 5
result = nth_fibonacci(n)
print(result)


def nth_fibonacci(n):
if n <= 1:
return n
Comment on lines +62 to +64

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggestion: Add input validation checks

Suggested change
def nth_fibonacci(n):
if n <= 1:
return n
def nth_fibonacci(n):
if not isinstance(n, int):
raise TypeError("Input must be an integer")
if n < 0:
raise ValueError("Input must be non-negative")
if n <= 1:
return n

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I have only positive integers in test cases so no need to these checks


# To store the curr Fibonacci number
curr = 0

# To store the previous Fibonacci numbers
prev1 = 1
prev2 = 0

# Loop to calculate Fibonacci numbers from 2 to n
for i in range(2, n + 1):

# Calculate the curr Fibonacci number
curr = prev1 + prev2

# Update prev2 to the last Fibonacci number
prev2 = prev1

# Update prev1 to the curr Fibonacci number
prev1 = curr

return curr

n = 5
result = nth_fibonacci(n)
print(result)

3 changes: 3 additions & 0 deletions test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@


# hello world