+ 1
Fibonacci Code not working
def fib(n): a, b = 0, 1 while a < n: print(a) a, b = b, a + b num = int(input()) fib(num) It doesn't output the complete value. Can anyone help look into this? #EDIT Write a program to take N (variable num in code template) positive numbers as input, and recursively calculate and output the first N numbers of the Fibonacci sequence (starting from 0).
8 odpowiedzi
+ 4
What it means complete value? What is your expected output.., for a sample?
+ 4
T0N1 Notify after any edit. According to task, First N numbers needed to print, but you are printing upto N. So that's may the problem..
Also this approach generates same output but try recursive way as per practice intention.
+ 3
I tried your code, works exactly the same without the function. As Jayakrishna 🇮🇳 have said: "what is your expected output?"
+ 1
def fib():
a = 0
b = 1
while True:
c = a
a = b
b = a + c
yield c
f = fib()
num = int(input('Enter no to generate: '))
for i in range(num):
print(next(f), end=' ')
+ 1
https://code.sololearn.com/c2JJ5i8KB9rr/?ref=app
This implementation defines a separate recursive function fib_recursive that returns a list of the first n numbers of the Fibonacci sequence. The function checks the base cases where n is 0, 1, or 2, and returns the appropriate lists of Fibonacci numbers. For larger values of n, it recursively calls itself to generate the sequence.
The fib function calls fib_recursive to get the sequence and then prints out each number in the sequence. Finally, the code prompts the user to enter a number and calls fib with the input as the argument.
0
change the while condition to this(as below) then you’ll get the right result
while n > 0:
print(a)
a, b = b, a + b
n -= 1