0

I found a code that recursively returns all combination of a list of 1 to n numbers with length k

def choose_iter(elements, length):
    for i in range(len(elements)):
        if length == 1:
            yield (elements[i],)
    else:
        for next in choose_iter(elements[i+1:len(elements)], length-1):
            yield (elements[i],) + next
def choose(l, k):
    return list(choose_iter(l, k))

this will return what I need but can I modify this so that I dont have to use the yield function? I haven't studied yield yet and I don't want to confuse myself with this.

WinnyDaPoo
  • 145
  • 7

2 Answers2

0

You can do it using itertools:

import itertools
for combination in itertools.combinations([i for i in range(1, n+1)], k):
    print(combination)

For n=7 and k=5, you have:

(1, 2, 3, 4, 5)
(1, 2, 3, 4, 6)
(1, 2, 3, 4, 7)
(1, 2, 3, 5, 6)
(1, 2, 3, 5, 7)
(1, 2, 3, 6, 7)
(1, 2, 4, 5, 6)
(1, 2, 4, 5, 7)
(1, 2, 4, 6, 7)
(1, 2, 5, 6, 7)
(1, 3, 4, 5, 6)
(1, 3, 4, 5, 7)
(1, 3, 4, 6, 7)
(1, 3, 5, 6, 7)
(1, 4, 5, 6, 7)
(2, 3, 4, 5, 6)
(2, 3, 4, 5, 7)
(2, 3, 4, 6, 7)
(2, 3, 5, 6, 7)
(2, 4, 5, 6, 7)
(3, 4, 5, 6, 7)
vvvvv
  • 25,404
  • 19
  • 49
  • 81
0

I think this should be the correct code

def choose_iter(elements, length):
    for i in range(len(elements)):
        if length == 1:
            yield (elements[i],)
        else:
            for j in choose_iter(elements[:len(elements)], length - 1):
                yield (elements[i],) + j
def choose(l, k):
    for i in choose_iter(l, k):
        print(i)

yield is similar to return but in this case, you need the yield statement otherwise the code will not work. You can check What does the "yield" keyword do? for more info.

And also avoid using "next" as a variable because it's also a python function.

Hope I helped.

Cristiano
  • 267
  • 2
  • 10