0

Good day. I was searching for how to list all possible combinations of numbers 1 to n taken k numbers. I cam across some algorithms and recursive methods. But I am fairly new to coding so I have a hard time understanding complex codes. Can someone tell me a way I can think of this problem so that I can put it into code? I am not allowed to use intertools so I may have to do an iterative or recursive version.

all_combination(3 , 2)

should return

[[1,2],[1,3],[2,3]]
WinnyDaPoo
  • 145
  • 7
  • The problem is called "Combinations N choose K". It is not trivial. One reference (not simple): https://stackoverflow.com/questions/127704/algorithm-to-return-all-combinations-of-k-elements-from-n – NoChance Oct 31 '20 at 13:27

1 Answers1

1

You can use:

from itertools import combinations 
list(combinations(range(1,n+1), k))

putting n=3, k=2 produces:

[(1, 2), (1, 3), (2, 3)]
Hamza
  • 5,373
  • 3
  • 28
  • 43