Give an algorithm (or direct Python code) that gives all sections of a collection of N elements in K-rolls, so that each bit has at least one element. I need this as in the case when the order matters, and where the order does not matter.
An example where order matters
>>> list(partition_n_in_k_bins_ordered((1,2,3,4), 2)) [([1], [2,3,4]), ([1,2], [3,4]), ([1,2,3], [4])] >>> list(partition_n_in_k_bins_ordered((1,2,3,4), 3)) [([1], [2], [3,4]), ([1], [2,3], [4]), ([1,2], [3], [4])] >>> list(partition_n_in_k_bins_ordered((1,2,3,4), 4)) [([1], [2], [3], [4])]
An example where order doesn't matter
>>> list(partition_n_in_k_bins_unordered({1,2,3,4}, 2)) [{{1}, {2,3,4}}, {{2}, {1,3,4}}, {{3}, {1,2,4}}, {{4}, {1,2,3}}, {{1,2}, {3,4}}, {{1,3}, {2,4}}, {{1,4}, {2,3}}]
These functions should create lazy iterators / generators, not lists. Ideally, they would use the primitives found in itertools . I suspect there is a smart solution that eludes me.
While I requested this in Python, I am also ready to translate a clear algorithm.