B.Sc Computer Science with Data Analytics
Python Programming - Lab
Core Lab 5
Bharathiar University
Program 7 - Write recursive functions for Fibonacci Sequence up to given number n.
SOURCE CODE:
def fibonacci(n, a=0, b=1):
if n == 0:
return []
elif n == 1:
return [a]
else:
if a + b > n:
return [a]
else:
return [a] + fibonacci(n, b, a + b)
# read a number
num = int(input("Enter a number to generate Fibonacci sequence up to that number: "))
# Check if the input is non-negative
if num < 0:
print("Please enter a non-negative number.")
else:
fib_sequence = fibonacci(num)
print("Fibonacci sequence up to", num, "is:", fib_sequence)
OUTPUT:
Enter a number to generate Fibonacci sequence up to that number: 5
Fibonacci sequence up to 5 is: [0, 1, 1, 2, 3]
No comments:
Post a Comment