[英]Listing all combination of list 1 to n given length restriction k
I found a code that recursively returns all combination of a list of 1 to n numbers with length k我找到了一个代码,它递归地返回长度为 k 的 1 到 n 个数字列表的所有组合
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?这将返回我需要的但我可以修改它以便我不必使用 yield 函数吗? I haven't studied yield yet and I don't want to confuse myself with this.我还没有研究过 yield ,我不想让自己与此混淆。
You can do it using itertools
:您可以使用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:对于n=7
和k=5
,您有:
(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)
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. yield 与 return 类似,但在这种情况下,您需要 yield 语句,否则代码将无法工作。 You can check What does the "yield" keyword do?您可以检查“yield”关键字有什么作用? for more info.了解更多信息。
And also avoid using "next" as a variable because it's also a python function.并且还要避免使用“next”作为变量,因为它也是一个 python 函数。
Hope I helped.希望我有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.