Answer:
My answer could not be submitted because of some signs and symbols in my solution.
So, I've added the answer and a comprehensive explanation as an attachment.
Note that the question is answered using Python programming language.
Explanation:
Lines that start with # are used to explain the program
See attachment