[英]Question about listing all possible combination given n and k (Python)
Good day.再会。 I was searching for how to list all possible combinations of numbers 1 to n taken k numbers.我正在寻找如何列出从 1 到 n 取 k 个数字的所有可能组合。 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.我不允许使用 intertools,所以我可能必须做一个迭代或递归版本。
all_combination(3 , 2)
should return应该回来
[[1,2],[1,3],[2,3]]
You can use:您可以使用:
from itertools import combinations
list(combinations(range(1,n+1), k))
putting n=3, k=2 produces:把 n=3, k=2 产生:
[(1, 2), (1, 3), (2, 3)]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.