Reputation: 43
I have this code, with input_number = 10
. I have to make a fibonacci sequence with condition: fibo[-2] < input_number < fibo[-1]
def fibonacci(input_number):
a = 0
b = 1
fibo=[a, b]
while b < input_number:
a, b = b, a+b
fibo.append(b)
print(fibo)
and the output was like this, just as I expected:
[0, 1, 1]
[0, 1, 1, 2]
[0, 1, 1, 2, 3]
[0, 1, 1, 2, 3, 5]
[0, 1, 1, 2, 3, 5, 8]
[0, 1, 1, 2, 3, 5, 8, 13]
But the problem now is that I want to call the last fibonacci number which is 13 and the output supposed to be "The last fibonacci number is 13 and it is the 8th fibonacci number"
. But I can't call the number of 13 because it is an integer and not a list.
How can I convert that into a list?
Upvotes: 1
Views: 1023
Reputation: 1
All the previous codes have a greater time complexity.
However, there is a separate way of doing it in constant time, if we consider the pow() or ** and sqrt() function to work in constant time.
Considering the series to be in the following format => 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, ...
Where,
0 ----> 0 th fibonacci number
1 ----> 1 th fibonacci number
1 ----> 2 th fibonacci number
2 ----> 3 rd fibonacci number
3 ----> 4 th fibonacci number
5 ----> 5 th fibonacci number
The mathematical formula to calculate the nth Fibonacci number in a constant time/O(1) is:
The python code should be something like this:
from math import sqrt
# n defines the nth fibonacci number
n = 5
def fib(n):
p = ( 1 + sqrt(5) ) / 2
q = ( 1 - sqrt(5) ) / 2
return int((p**n-q**n) / sqrt(5))
# to counter float value from the division operator int is used
print(fib(n))
Input:
5
Output:
5
Upvotes: 0
Reputation: 4754
You probably just need the syntax to access the fibo array. Hope the below helps:
def fibonacci(input_number):
a = 0
b = 1
fibo = [a, b]
while b < input_number:
a, b = b, a + b
fibo.append(b)
print(fibo)
print(f'fibonacci number {len(fibo)} is {fibo[len(fibo) - 1]}')
print('===')
i = 0
while i < len(fibo):
print(f'fibonacci number {i + 1} is {fibo[i]}')
i += 1
fibonacci(10)
Result:
[0, 1, 1]
[0, 1, 1, 2]
[0, 1, 1, 2, 3]
[0, 1, 1, 2, 3, 5]
[0, 1, 1, 2, 3, 5, 8]
[0, 1, 1, 2, 3, 5, 8, 13]
fibonacci number 8 is 13
===
fibonacci number 1 is 0
fibonacci number 2 is 1
fibonacci number 3 is 1
fibonacci number 4 is 2
fibonacci number 5 is 3
fibonacci number 6 is 5
fibonacci number 7 is 8
fibonacci number 8 is 13
Upvotes: 0
Reputation: 430
fibo
is the list containing all of your values. To get the last value of the list you can index it by -1, so fibo[-1]
. We can then determine which Fibonacci number fibo[-1] is by getting the length of the list, len(fibo)
.
I wont write the full answer for you, but put this
print("fibo[-1]==",fibo[-1], " len(fibo)==", len(fibo))
outside the while loop, and I think you'll be able to figure it out from there.
Upvotes: 0