I am writing a function that should output all k-way partitions of a list A. This problem is clearly recursive, and the implementation should be straightforward:
def gen_partition_k_group( A, k):
#
if len(A) == 0 :
# EDITED FOLLOWING SUGGESTION
yield [ [] for _ in xrange(k) ]
#
else :
# all k-partitions of the list of size N-1
for ss in gen_partition_k_group(A[:-1], k) :
assert( sum( len(gg) for gg in ss ) == len(A) -1 )
for ii in xrange(k) :
tt = list(ss)
print tt
tt[ ii ].append( A[ -1 ] )
print tt
assert( sum( len(gg) for gg in tt ) == len(A) )
yield tt
A = range(3)
k = 2
[ xx for xx in gen_partition_k_group( A, k) ]
Output
AssertionError:
[[], []]
[[0], [0]]
I don't understand the output. It should be [[0], []]
instead of [[0], [0]]
. What am I missing?
NB: I know how to write a different function without append
which outputs the correct result. Iterator over all partitions into k groups? (first answer)
What I don't understand is the behaviour of this particular function.