Working solution for the third question (Part B) of the project