Subscribe Us

Finding the nth element of Fibonacci Series. (Dynamic Programming) (Python)

This is the code without any modification.

def dinamicProgramming(n):
    if n == 1 or n == 2return 1
    return dinamicProgramming(n-1) + dinamicProgramming(n-2)

print(dinamicProgramming(5)) #5
print(dinamicProgramming(6)) #8
print(dinamicProgramming(10)) #55
print(dinamicProgramming(100)) #354224848179261915075


In the above code first three print statement works fine but in the fourth print statement it got stuck, Because 100 is very big number.

But we can solve this problem with the help of Dynamic Programming.

With adding some lines of code.


This is the code with some modifications.

def dinamicProgramming(nmemo={}):
    if n in memo: return memo[n]
    if n == 1 or n == 2return 1
    memo[n] = dinamicProgramming(n-1) + dinamicProgramming(n-2)
    return dinamicProgramming(n-1, memo) + dinamicProgramming(n-2, memo)

print(dinamicProgramming(5)) #5
print(dinamicProgramming(6)) #8
print(dinamicProgramming(10)) #55
print(dinamicProgramming(100)) #354224848179261915075


And now it works fine and give the result very quickly.


Finding the nth element of Fibonacci Series. (Dynamic Programming) (Python) Finding the nth element of Fibonacci Series. (Dynamic Programming) (Python) Reviewed by Coding Arc on August 17, 2021 Rating: 5

No comments:

Powered by Blogger.