Well friends, I've already figured out a way to shorten the program from 55 lines down to 46, and that was to define the ones place not by means of a while loop, but by slicing an array. Here is the result (lines 1 and 2 are unchanged), hopefully you can read it:
If not, here is the relevant code: