1# By recursion
2def fib(n):
3 if n == 1 or n == 2:
4 return 1
5 else:
6 return(fib(n-1) + fib(n-2))
7
8n = 6
9for i in range(1,n+1):
10 print(fib(i))
1def Fibonacci( pos ):
2 #check for the terminating condition
3 if pos <= 1 :
4 #Return the value for position 1, here it is 0
5 return 0
6 if pos == 2:
7 #return the value for position 2, here it is 1
8 return 1
9
10 #perform some operation with the arguments
11 #Calculate the (n-1)th number by calling the function itself
12 n_1 = Fibonacci( pos-1 )
13
14 #calculation the (n-2)th number by calling the function itself again
15 n_2 = Fibonacci( pos-2 )
16
17 #calculate the fibo number
18 n = n_1 + n_2
19
20 #return the fibo number
21 return n
22
23#Here we asking the function to calculate 5th Fibonacci
24nth_fibo = Fibonacci( 5 )
25
26print (nth_fibo)
1# Python program to display the Fibonacci sequence
2
3def recur_fibo(n):
4 if n <= 1:
5 return n
6 else:
7 return(recur_fibo(n-1) + recur_fibo(n-2))
8
9nterms = 10
10
11# check if the number of terms is valid
12if nterms <= 0:
13 print("Plese enter a positive integer")
14else:
15 print("Fibonacci sequence:")
16 for i in range(nterms):
17 print(recur_fibo(i))
18
1# WARNING: this program assumes the
2# fibonacci sequence starts at 1
3def fib(num):
4 """return the number at index num in the fibonacci sequence"""
5 if num <= 2:
6 return 1
7 return fib(num - 1) + fib(num - 2)
8
9
10print(fib(6)) # 8
1#fibonacci sequence with memory to increase the speed.
2class recur_fibo:
3 memory = {0: 1, 1:1}
4
5 def fibonacci(n):
6 if n in recur_fibo.memory:
7 return recur_fibo.memory[n]
8 else:
9 recur_fibo.memory[n] = recur_fibo.fibonacci(n-1) + recur_fibo.fibonacci(n-2)
10 return recur_fibo.memory[n]
11
12if __name__ == "__main__":
13 value = recur_fibo.fibonacci(200)
14 print(value)