Solution for Problem 12

def need to optimize more.
[Finished in 9.5s]