(d) Write the following functions: i. fib( n ) that returns the nth term of a Fibonacci, \( \mathrm{f}(\mathrm{n}) \), sequence, given that: \[ f(1)=1 ; f(2)=1 ; f(n)=f(n-\mathbf{1})+f(n-2), n \geq 3 \] ii. fibSum ( n ) that returns the sum of the first n terms of a Fibonacci sequence. Utilize the previous function. iii. fibRatio ( n ) that returns the ratio \( \mathrm{f}(\mathrm{n}+1) \mathrm{f}(\mathrm{n}), \mathrm{n} \geq 1 \). Utilize the first function. [ 2 marks] iv. Assuming that the three functions are in one program saved as mod. py in a folder called mods and you create a program in the same folder as the folder. Demonstrate how you would import the package into your program. Print the following in the program. Do it twice by first using importing the package and secondly by importing the module inside the package (as m). The tenth term of the Fibonacci sequence. The sum of the first 10 terms of the sequence and the 11 th term divided by the 10th term. The printed message should be: \( [6 \) marks \( ] \) The 10 th term is 55, the sum is 143 and the ratio is 1.6181818181818182 .
Real Tutor Solution
Answer
Solution
Sign in to Unlock Answers for Free!
A Learning Platform Trusted by Millions of Real Students and Teachers.
Reviewed and approved by the UpStudy tutoring team
Bonus Knowledge
```python # fib function to calculate nth Fibonacci number def fib(n): if n == 1 or n == 2: return 1 return fib(n - 1) + fib(n - 2) # fibSum function to calculate the sum of the first n Fibonacci numbers def fibSum(n): total = 0 for i in range(1, n + 1): total += fib(i) return total # fibRatio function to calculate the ratio of f(n+1) to f(n) def fibRatio(n): return fib(n + 1) / fib(n) # Assuming you have saved this as mod.py inside a folder called mods ``` *Example of importing the package and printing the required outputs:* ```python # First method of importing the package from mods import mod # Printing results using the package print(f"The 10th term is {mod.fib(10)}, the sum is {mod.fibSum(10)} and the ratio is {mod.fibRatio(10)}.") # Second method of importing the module inside the package as 'm' import mods.mod as m # Printing results using the module print(f"The 10th term is {m.fib(10)}, the sum is {m.fibSum(10)} and the ratio is {m.fibRatio(10)}.") ``` When you run this code, you'll see the output: ``` The 10th term is 55, the sum is 143 and the ratio is 1.6181818181818182. The 10th term is 55, the sum is 143 and the ratio is 1.6181818181818182. ```