-1

Suppose you have a set of n objects, and you want to list its k-element subsets (that is, its subsets with exactly m elements) solved by Recursive functions without using list(itertools.combinations) for example k_subsets({1,2,3},2 ) show the

[{1, 2}, {1, 3}, {2, 3}]
Amin Amin
  • 13
  • 3

1 Answers1

0

This will be the code of combination using recursion, and this will give you all the subsets of given list and the subsets of desired length.

l1 = [1, 2, 3]
s = 2
unique = []
def combination(set):
    if set == []:
        return [[]]

    sub = combination(set[1:])
    # This will give you all the subsets of given list and This is also the return variable of the function.
    all_combination = (sub + [[set[0]] + x for x in sub])
    ########################################################
    # This for loop will give you a subsets of desire length.
    for i in range(len(all_combination)):
        if int(len(all_combination[i])) == s and all_combination[i] not in unique:
            unique.append(all_combination[i])
    #########################################################
    return all_combination

print(combination(l1))
print(unique)

Output

  • Fine, answer is true but not a exact answer of my questions. I want the code that just appear these '[{1, 2}, {1, 3}, {2, 3}]' not all. Just because we work with subset not ordered pair. For example [{1,1}] is not acceptable because we used 1 once or {1,2} and {2,1} is the same. – Amin Amin Jun 06 '20 at 06:12
  • @AminAmin now check i have updated my answer. This is according to your desire. – Ali Hassan Ahmed Khan Jun 06 '20 at 13:29