It seems to me that a lot of this could be done using sklearn.utils.gen_even_slices.