Generating combinations with repetitions
Remco Gerlich
scarblac-spamtrap at pino.selwerd.nl
Thu May 4 03:06:19 EDT 2000
Tomaz Ficko wrote in comp.lang.python:
> Can someone post code for generating all combinations of k elements out of n
> elements with repetitions.
>
> Example:
> elements = 1,2,3,4 and k=3
>
> 111, 112, 113, 114,
> 222, 221, 223, 224,
> 333, 331, 332, 334,
> 444, 441, 442, 443,
> 123, 124, 134, 234
def combs(elements, k):
length = len(elements)
# Compute the numer of combinations
n = long(length) ** k
result = []
for combination in xrange(n):
onecomb = []
for digit in range(k):
onecomb.append(str(elements[combination % length])
combination = combination / length
result.append(onecomb)
return result
Basically, it lists the numbers 0 to length**k, written in a base that uses
'elements' as its digits.
--
Remco Gerlich, scarblac at pino.selwerd.nl
"This gubblick contains many nonsklarkish English flutzpahs, but the
overall pluggandisp can be glorked from context" (David Moser)
More information about the Python-list
mailing list