Python solution

Well, it's just a direct rewrite of the JavaScript one with a different syntax, but Python is cool so here goes.