Generating combinations with repetitions
Jeff Raven
jraven at psu.edu
Thu May 4 05:58:21 EDT 2000
On Thu, 4 May 2000 10:29:50 +0200, Tomaz Ficko <tomaz.ficko at agroruse.si> wrote:
>This is not quite what I meant. I want it to generate combinations not
>variations, order of the elements is irrelevant.
>Example: 121 is equal to 211 or 112.
>Anyway thanks.
>
>Tomaz
>
Ah. Then perhaps the following will do.
Jeff Raven
------ Code ------
def rchoices(n, k) :
# Returns a list consisting of all k-element subsets
# of {1 ... n} -- with repetitions.
result = []
if k <= 0 :
return result
current = [1] * k
while 1 :
result.append(current[:])
index = k - 1
while index >= 0 :
if current[index] < n :
break
index = index - 1
else:
break
current[index] = current[index] + 1
while index < k - 1 :
current[index + 1] = current[index]
index = index + 1
return result
More information about the Python-list
mailing list