+ 2
Help me with 'fibonacci sequence' code
The Fibonacci sequence is one of the most famous formulas in mathematics. Each number in the sequence is the sum of the previous two numbers. For example, this is what the Fibonacci sequence looks like for 10 numbers, starting with 0: 0,1,1,2,3,5,8,13,21,34. Write a program that uses the Nth (variable num in the code template) positive number as input, recursively calculates and outputs the first Nth numbers of the Fibonacci sequence (starting from 0). Sample input 6 Result example 0 1 1 2 3 8 If you are composing a Fibonacci sequence for n numbers, then you need to use the condition n <= 1 as a base case. https://code.sololearn.com/cMppMTkMjh0K/?ref=app
16 ответов
+ 10
num = int(input())
def fibonacci(n):
if n<=1:
return n
else:
return fibonacci(n-1)+fibonacci(n-2)
for a in range(num):
print(fibonacci(a))
+ 4
num = int(input())
d = 0
f = 1
def fibonacci(n,d,f):
if n == 1:
print(d)
else:
print(d)
d2 = d
d=d+f
f=d2
return fibonacci(n-1,d,f)
#complete the recursive function
fibonacci(num,0,1)
this worked for me
trial and error rocks :)
+ 2
#my code it worked
#i copied from IP text book
num = int(input())
a=0
b=1
print(a)
print(b)
for i in range(1,num-1):
c=a+b
print(c)
a,b=b,c
+ 1
Amaklia Ilkama sorry, but this code doesn't give us Fibonacci
+ 1
Azizkxon Murotkhonov Here it is. I've fixed my code. If you have questions I'll explain
https://code.sololearn.com/cSH87lyS7mAM/?ref=app
+ 1
num = int(input())
def fib(a,b,c):
if c == 1:
print(a)
else:
print(a)
ab,a = a,a+b
b = ab
return fib(a,b,c-1)
fib(0,1,num)
0
Nicko12 , when entering the number 'n', the program must read and output n numbers from the sequence
0
You can write a recursive function for it . For example this code is the best recursive function code for fibonacci.
Remember : recursive function take lot of time and memory , so don't input big numbers for it .
def fibonacci(n):
if n <= 1:
return n
else:
return fibonacci( n-1)+fibonacci (n -2)
x=int(input())
print(fibonacci(x))
This code gives us fibonacci .
0
Azizkxon Murotkhonov Sorry, I made a mistake about my code earlier😐, Anyway follow Amaklia Ilkama's code, it's the correct one for fibonacci sequence. I'll fix my code.
0
i tried but on input 5 the code outputs 5 when it should output 0, 1, 1, 2, 3
0
Ok
0
num = int(input())
def recur_fibo(n):
if n <= 1:
return n
else:
return(recur_fibo(n-1) + recur_fibo(n-2))
for i in range(num):
print(recur_fibo(i))
0
@Abhiraj can you explain about the code?
0
num = int(input())
def fibonacci(n):
if n in {0, 1}: # Base case
return n
else:
return fibonacci(n - 1) + fibonacci(n - 2)
for a in range(num):
print(fibonacci(a))
fibonacci(num)
0
num = int(input());
def fibonaci(n):
a = 1
b = 0
c = 0
for _ in range(n):
print(b)
c = b + a
b = a
a = c
fibonaci(num)
- 1
Nicko12 can you reread an example?