Skip to content Skip to sidebar Skip to footer

Using Recursion To Create A List Combination

I'm in trouble creating a combination of elements from list. What i would like to do is to create a recursive function in Python which returns a combination of elements for example

Solution 1:

This can be done in this way :

defcombination(l,n, mylist=[]):
    ifnot n:  print(mylist)
    for i inrange(len(l)):
        mylist.append(l[i])
        combination(l[i+1:], n-1, mylist)
        mylist.pop()

l = ["A","B","C","D","E","F","G","H"]
n=4
combination(l, n)

Solution 2:

For each element x in a, generate all k-1 combinations from the elements right to it, and prepend x to each one. If k==0, simply return one empty combination, thus exiting the recursion:

def combs(a, k):
    if k == 0:
        return[[]]
    r = []
    for i, x in enumerate(a):
        for c in combs(a[i+1:], k - 1):
            r.append([x] + c)
    #print'\t' * k, k, 'of', a, '=', r
    return r

Uncomment the "print" line to see what's going on.

As a side note, it's better to use English variable and function names, just for the sake of interoperability (your very question being an example).

Post a Comment for "Using Recursion To Create A List Combination"