For example, I'm working on a method that given a certain size "k", and an integer "n" I can generate subsets from {1...n} with "k" length.
This is my code so far:
def combinations(k,lista,comb): if(len(comb)==k): print(comb) else: for i in range(len(lista)): combinations(k,lista,comb + str(lista[i])) def starter(n,k): lista = [] for i in range(1,n+1): lista.append(i) combinations(k,lista,"") starter(5,3) The output of starter(5,3) is:
111 112 113 114 115 121 122 123 124 125 131 132 133 134 135 . . . 545 551 552 553 554 555 My problem is that it is repetitive, as you see I have 545 and 554 in the output(and 455;not shown), while in this case ordering shouldn't matter, therefore I should keep either 545 or 554 or 455. I also have 332 in the output as well as 323 and 233, these three are considered "duplicates" and I need to keep only one.
How can my code be modified to filter for this?
Edit: in my code "k" was "m", I fixed it to avoid misconceptions.
Edit2: I do understand that I can use itertools, but I am trying to solve everything(for now) without depending on libraries or packages.
itertools.combinationsfrom Python standard lib.itertools.combinations()will not have545,554or455to begin with, so it is definitely not a viable solution!545a valid output (since it has 5 twice, it is not technically a subset). This is the difference betweenitertools.combinationsanditertools.combinations_with_replacement.