Reputation: 51
Hello I am trying to write a script that prompts the user for an integer number (n), then prints all the Fibonacci numbers that are less than or equal to the input, in that order. EXAMPLE:
Enter a number : 14
output is: 1 1 2 3 5 8 13
Here is what i have so far but not sure if it is the most efficient way? It is working correctly but I was wondering if there is a easier way to clean this up..
n = int(input("Enter a number: "))
a = 0
b = 1
sum = 0
while(sum <= n):
print(sum, end = " ")
count += 1
a = b
b = sum
sum = a + b
print(end = " ")
I am fairly new to python and am doing some practice but was not able to find a solution in textbook.
Upvotes: 0
Views: 6755
Reputation: 9
I give thanks to tboschi. His code helped me solve this question.
# fibonacci_list = [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, ...]
fibonacci_list = [0, 1]
for value in fibonacci_list:
if value < 1000000:
new_value = fibonacci_list[-1] + fibonacci_list[-2]
fibonacci_list.append(new_value)
def fibonacci(n):
# Type your code here.
if n >= 0:
for index_num in range(len(fibonacci_list)):
if n == index_num:
return fibonacci_list[index_num]
else:
return -1
if __name__ == '__main__':
start_num = int(input())
print('fibonacci({}) is {}'.format(start_num, fibonacci(start_num)))
Upvotes: 0
Reputation: 1141
I don't really like the the approaches above, as number sequences are infinite and memory allocation is not. Thus in order to effectively get the highest possibly computable numbers (by your computer of course), one should definetly use generators.
ITERATIONS = 100
def fibo():
a, b = 0, 1
while True:
a, b = b, a + b
yield b
f = fibo()
for _ in range(ITERATIONS):
print(next(f))
! But please bear in mind, that your computer will 100% crash if you attempt something like list(f)
as the number sequence is infinite, and your computer power & storage is not.
Have a good one.
Upvotes: 0
Reputation: 41
This way is efficient enough, but your code can do better
n = int(input("Enter a number: "))
a = b = 1
while(b <= n):
print(b, end = " ")
a, b = b, a + b
Upvotes: 1
Reputation: 124
Someting like this?
n = int(input("Enter a number: "))
fib = [0, 1]
while fib[-1] + fib[-2] <= n:
fib.append(fib[-1] + fib[-2])
print(fib)
It depends on what you mean by "most efficieny way". Fibonacci is a fairly typical coding exercise, most of the time used to explain recursion. See this answer for example.
Upvotes: 1