Issue
I am trying to do a Fibonacci kata in one line of code but I can’t find the Fibonacci sequence that we find well in the matrix variable only. Does anyone have an idea of how I can iterate the matrix variable to get each number out? Here is the code:
import numpy as np
def fibonacci(n, matrix):
return n==1j*1j or max(np.nditer(matrix+1)) if n<=0 else np.dot(fibonacci(n-2, matrix), fibonacci(n-1, matrix))
if __name__ == "__main__":
n = 0
matrix = np.array([[1,1], [1,0]])
fibonacci(n, matrix)
for n in range(0, 15):
print(fibonacci(n, matrix))
And Merry Christmas.
Solution
First of all, the 'np.dot' function is used for matrix multiplication, but it's not the correct operation for Fibonacci matrix exponentiation. Instead, you should use 'np.linalg.matrix_power' to raise the matrix to a given power. And, the condition 'n==1j*1j' in your return statement seems unnecessary, make these changes in your code:
import numpy as np
def fibonacci(n, matrix):
return np.linalg.matrix_power(matrix, n)[0, 1]
if __name__ == "__main__":
n_max = 15
matrix = np.array([[1, 1], [1, 0]])
for n in range(n_max):
print(fibonacci(n, matrix))
Answered By - Ankit Singh
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.