Slightly more readable Python version at https://gist.github.com/grenkoca/b82281a4706e936072979acf54b...