Hello everyone! This is Part 3 of practice questions for the upcoming Quiz 03 on Tuesday, November 10th. Part 1 (already posted) covered OOP code writing questions, Part 2 covered OOP memory diagrams, and this will be focusing on recursion memory diagram practice. The solutions for these problems can be found here. Good luck :)
Instructions
Please create a memory diagram for each problem documenting the entire execution of the program like you have practiced in class.
Review Problems
This combines OOP with Lists and recursion!
1. Ball is Life
from __future__ import annotations
from typing import List
class Baller:
"""Class for a basketball player."""
name: str
avg: float
def __init__(self, name: str, avg: float):
"""Constructor for Student class."""
self.name = name
self.avg = avg
def team_sum(team: List[Baller]) -> float:
"""Adds averages of all players."""
if len(team) == 0:
return 0
else:
points: float = team[len(team) - 1].avg
team.pop()
return points + team_sum(team)
def main() -> None:
"""Entrypoint of program."""
b1: Baller = Baller("Cole", 18.7)
b2: Baller = Baller("Bacot", 12.3)
b3: Baller = Baller("Francis", 0.1)
ballers: List[Baller] = [ b1, b2, b3 ]
total: float = team_sum(ballers)
print("Average is: " + str(total / 3))
print(ballers)
if __name__ == "__main__":
main()
2. Christmas Fun
This one is kind of challenging…
def fun_math(x: int, y: str) -> int:
if x <= 0:
return 1
elif len(y) > 5:
return x * fun_math(x - 2, "Santa") * fun_math(x - 3, "Clause")
else:
return x + fun_math(x - 1, "Rudolph") + fun_math(x - 2, "Snow")
def main() -> None:
"""Entrypoint of program."""
x: int = 5
y: str = "Christmas"
z: int = fun_math(x, y)
if __name__ == "__main__":
main()