简体   繁体   English

关于列出给定 n 和 k 的所有可能组合的问题(Python)

[英]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.

相关问题 列出给定长度限制 k 的列表 1 到 n 的所有组合 - Listing all combination of list 1 to n given length restriction k 关于返回组合 N 取 K 的问题 - Question about returning combination N taken K 如何形成给定数字的所有可能组合以形成不重复数字的n位数字?(python) - How to form all possible combination of given digits to form a n-digit number without repetition of digits?(python) 查找 n 个元素的所有 k 个组合长度 - Find all k combination length of n elements 从 python 中的给定单词列表创建所有可能组合的列表 - creating a list of all possible combination from a given list of words in python 给定一个数字,生成长度为n的X和O的所有可能组合的列表 - Given a number, generate a list of all possible combination of X and O with length n 从给定的单词列表中生成具有“N”长度的所有可能组合(寻找不重复) - Generate all possible combination with “N” length from given words list (Looking for no repeat) 给定列表的所有可能的列表组合 - All possible combination of lists for a given list 给定一个范围列表,找到这些范围的所有组合,总和为 k - Given a list of ranges, find all combination for these ranges that sums upto k 来自n个大小列表的k个大小的python组合(递归) - python combination of k size from n size list (recursive)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM