[英]creating selections from the elements of a list using a general number of nested loops
我正在尝试创建一个函数,该函数将列表作为输入并返回列表中特定数量元素的所有可能选择,而不使用itertools
的内置combination()
函数。
例如,如果我们将list [1,2,3,4]
和数字 3 传递给这样的函数,该函数应该返回[[1,2,3],[1,2,4],[1,3,4],[2,3,4]]
如果要选择的元素数为 3,我已经创建了此函数的一个版本,但我不知道如何处理嵌套 for 循环和比较的通用数量。
我的代码:
sample_set = [1,2,3,4]
def selections(input_set, number):
if number == 3:
#frozensets are used here so a set of sets can be generated and so that frozensets containing the same elements in different order can be removed when we apply set()
frozenset_list = [frozenset((i, j, k)) for i in input_set for j in input_set for k in input_set if i != j !=k !=i ]
unique_frozenset_list = set(frozenset_list) #removing identical frozensets
return [list(i) for i in unique_frozenset_list] #converting all frozensets to lists
print(selections(sample_set, 3))
我有一个索引组合要删除,所以如果你想要 5 个列表中的 3 个项目,我可以删除两个索引的组合,例如(2,5)
我加入了一些条件以确保没有重复项,并且列表的长度将达到最大值,即 nCr, nCr
是一个数学公式。
然后我会使用这些组合来制作不包含这些组合索引的列表,并添加到主列表final_list
import random
import math
def go(sample_set,num):
new_list = []
n = len(sample_set)
r = len(sample_set) - num
nCr = (math.factorial(n) / math.factorial(r) / math.factorial(n - r))
while len(new_list) < int(nCr):
co = [random.randint(0,len(sample_set)-1) for count in range(r)]
if len(co) == len(set(co)) and co not in new_list:
new_list.append(co)
final_list = []
for x in new_list:
combination = [q for q in sample_set if sample_set.index(q) not in x]
final_list.append(combination)
return sorted(final_list) # sorted is optional
print(go([1, 2, 3, 4],3))
>>> [[1, 2, 3], [1, 2, 4], [1, 3, 4], [2, 3, 4]]
print(go([1, 2, 3, 4, 5],3))
>>> [[1, 2, 3], [1, 2, 3], [1, 2, 4], [1, 2, 5], [1, 4, 5], [1, 4, 5], [2, 3, 4], [2, 3, 4], [2, 3, 5], [3, 4, 5]]
我刚刚意识到我可以向前而不是向后做,因为只需获取 3 个索引(或任何给定的数字)的所有可能组合并基于此打印一个列表。
def go(sample_set,num):
new_list = []
n = len(sample_set)
nCr = (math.factorial(n) / math.factorial(num) / math.factorial(n - num))
while len(new_list) < int(nCr):
co = [random.randint(0,len(sample_set)-1) for count in range(num)]
if len(co) == len(set(co)) and co not in new_list:
new_list.append(co)
final_list = []
for x in new_list:
combination = [q for q in sample_set if sample_set.index(q) in x]
final_list.append(combination)
return sorted(final_list) # sorted is optional
print(go([1, 2, 3, 4],3))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.