Pregunta
upstudy study bank question image url

(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 .

Ask by Young Ryan. in Kenya
Feb 03,2025

Solución de tutoría real

Respuesta verificada por el tutor

Responder

```python # mod.py def fib(n): if n == 1 or n == 2: return 1 else: return fib(n - 1) + fib(n - 2) def fibSum(n): total = 0 for i in range(1, n + 1): total += fib(i) return total def fibRatio(n): return fib(n + 1) / fib(n) ``` **main.py:** ```python # main.py # First Method: Importing the entire module through the package import mods.mod # Using the functions with full module path term_10 = mods.mod.fib(10) sum_10 = mods.mod.fibSum(10) ratio_10 = mods.mod.fibRatio(10) print(f"The 10th term is {term_10}, the sum is {sum_10} and the ratio is {ratio_10}.") # Second Method: Importing the module with an alias from mods import mod as m # Using the functions with the alias term_10_m = m.fib(10) sum_10_m = m.fibSum(10) ratio_10_m = m.fibRatio(10) print(f"The 10th term is {term_10_m}, the sum is {sum_10_m} and the ratio is {ratio_10_m}.") ``` **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. ```

Solución

Certainly! Below are the implementations for each part of your problem, including the functions `fib`, `fibSum`, `fibRatio`, and the demonstration of importing the module in two different ways. --- ### **i. `fib(n)` Function** This function computes the nth term of the Fibonacci sequence using recursion. ```python # mod.py def fib(n): if n == 1 or n == 2: return 1 else: return fib(n - 1) + fib(n - 2) ``` --- ### **ii. `fibSum(n)` Function** This function calculates the sum of the first `n` terms of the Fibonacci sequence by utilizing the `fib` function. ```python # mod.py def fibSum(n): total = 0 for i in range(1, n + 1): total += fib(i) return total ``` --- ### **iii. `fibRatio(n)` Function** This function computes the ratio \( \frac{f(n+1)}{f(n)} \) using the `fib` function. ```python # mod.py def fibRatio(n): return fib(n + 1) / fib(n) ``` --- ### **iv. Importing the Module and Using the Functions** Assuming the three functions are saved in a file named `mod.py` inside a folder called `mods`, and you have another Python script in the same parent directory, here's how you can import and use the functions in two different ways. **Folder Structure:** ``` your_project/ │ ├── mods/ │ ├── __init__.py │ └── mod.py │ └── main.py ``` **Contents of `mod.py`:** ```python # mods/mod.py def fib(n): if n == 1 or n == 2: return 1 else: return fib(n - 1) + fib(n - 2) def fibSum(n): total = 0 for i in range(1, n + 1): total += fib(i) return total def fibRatio(n): return fib(n + 1) / fib(n) ``` **Ensure `__init__.py` Exists:** To make `mods` a package, ensure there's an `__init__.py` file inside the `mods` folder. It can be empty or can contain initialization code. ```python # mods/__init__.py # This file can be left empty ``` **Importing and Using the Module in `main.py`:** ```python # main.py # First Method: Importing the entire module through the package import mods.mod # Using the functions with full module path term_10 = mods.mod.fib(10) sum_10 = mods.mod.fibSum(10) ratio_10 = mods.mod.fibRatio(10) print(f"The 10th term is {term_10}, the sum is {sum_10} and the ratio is {ratio_10}.") # Second Method: Importing the module with an alias from mods import mod as m # Using the functions with the alias term_10_m = m.fib(10) sum_10_m = m.fibSum(10) ratio_10_m = m.fibRatio(10) print(f"The 10th term is {term_10_m}, the sum is {sum_10_m} and the ratio is {ratio_10_m}.") ``` **Output When Running `main.py`:** ``` 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. ``` --- ### **Explanation:** 1. **Function Implementations:** - `fib(n)`: Recursively calculates the nth Fibonacci number. - `fibSum(n)`: Iteratively sums up the first `n` Fibonacci numbers by calling `fib(i)` for each term. - `fibRatio(n)`: Computes the ratio of the (n+1)th term to the nth term. 2. **Import Methods:** - **First Method (`import mods.mod`):** This imports the `mod` module from the `mods` package. Functions are accessed using the full path `mods.mod.function_name`. - **Second Method (`from mods import mod as m`):** This imports the `mod` module with an alias `m`, allowing functions to be accessed as `m.function_name`. 3. **Printing the Results:** - Both methods are used to print the same results, demonstrating that both import techniques are effective and produce identical outputs. This setup ensures modularity and reusability of your Fibonacci functions across different programs within the same project.

Revisado y aprobado por el equipo de tutoría de UpStudy

error msg
Explicar
Simplifique esta solución

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. ```

preguntas relacionadas

Latest Computer Technology Questions

¡Prueba Premium ahora!
¡Prueba Premium y hazle a Thoth AI preguntas de matemáticas ilimitadas ahora!
Quizas mas tarde Hazte Premium
Estudiar puede ser una verdadera lucha
¿Por qué no estudiarlo en UpStudy?
Seleccione su plan a continuación
Prima

Puedes disfrutar

Empieza ahora
  • Explicaciones paso a paso
  • Tutores expertos en vivo 24/7
  • Número ilimitado de preguntas
  • Sin interrupciones
  • Acceso completo a Respuesta y Solución
  • Acceso completo al chat de PDF, al chat de UpStudy y al chat de navegación
Básico

Totalmente gratis pero limitado

  • Solución limitada
Bienvenido a ¡Estudia ahora!
Inicie sesión para continuar con el recorrido de Thoth AI Chat
Continuar con correo electrónico
O continuar con
Al hacer clic en "Iniciar sesión", acepta nuestros términos y condiciones. Términos de Uso & Política de privacidad