Morgan Stanley Interview Question

solve this problem in python