Python lab program 2
Python lab program 2
Part A
Develop a program to generate Fibonacci sequence of length (N).Read N from
the console.
def fibonacci_numbers(num):
if num == 0:
return 0
elif num == 1:
return 1
else:
# printing fibonacci numbers
return fibonacci_numbers(num - 2) + fibonacci_numbers(num - 1)
Algorithm:
Step 1:
Start
Step 2:
Define a function fibonacci_numbers(num)
If num == 0, return 0
Else if num == 1, return 1
Else return fibonacci_numbers(num - 1) + fibonacci_numbers(num - 2)
Step 3:
Prompt the user to enter a number n
Step 4:
Convert the input to an integer
Step 5:
Loop from i = 0 to i < n
Call the function fibonacci_numbers(i)
Print the result (on the same line)
Step 6:
End
Example in Algorithmic Notation:
Function fibonacci_numbers(num)
If num == 0:
Return 0
Else if num == 1:
Return 1
Else:
Return fibonacci_numbers(num - 1) + fibonacci_numbers(num - 2)
End Function
Start
Read n
For i ← 0 to n - 1 do
Print fibonacci_numbers(i)
End For
End
Output:
Enter the number: 5
01123
Part B
Write a function to calculate factorial of a number. Develop a program to
compute binomial coefficient(Given N and R).
def factorial(z):
if z == 1 or z == 0: # Added base case for 0
return 1
else:
return z * factorial(z - 1)
Algorithm:
Step 1: Start
• Compute factorial(k)
• Compute factorial(n - k)
• Return a
Step 4: Input n from the user
Step 8: End
Function binomial_coefficient(n, k)
num ← factorial(n)
denom ← factorial(k) * factorial(n - k)
Return num / denom
End Function
Start
Read n
Read k
f ← factorial(n)
c ← binomial_coefficient(n, k)
Print "The factorial of n is: ", f
Print "The binomial coefficient is: ", c
End
Output:
Enter the number n: 5
Enter the r value (k): 2
The factorial of n is: 120
The binomial coefficient C(n, k) is: 10.0