【发布时间】:2020-05-20 16:10:07
【问题描述】:
我想生成列表中元素的排列,但只保留一个集合,其中每个元素在每个位置上只出现一次。
例如 [1, 2, 3, 4, 5, 6] 可能是一个用户列表,我想要 3 个排列。一个好的集合是:
[1,2,3,5,4,6]
[2,1,4,6,5,3]
[3,4,5,1,6,2]
但是,例如,不能将 [1,3,2,6,5,4] 添加到上面,因为有两个排列,其中 1 出现在第一个位置两次,5 也会出现在第一个位置第五个位置两次,但是其他元素只出现在这些位置上一次。
到目前为止我的代码是:
# this simply generates a number of permutations specified by number_of_samples
def generate_perms(player_list, number_of_samples):
myset = set()
while len(myset) < number_of_samples:
random.shuffle(player_list)
myset.add(tuple(player_list))
return [list(x) for x in myset]
# And this is my function that takes the stratified samples for permutations.
def generate_stratified_perms(player_list, number_of_samples):
user_idx_dict = {}
i = 0
while(i < number_of_samples):
perm = generate_perms(player_list, 1)
for elem in perm:
if not user_idx_dict[elem]:
user_idx_dict[elem] = [perm.index(elem)]
else:
user_idx_dict[elem] += [perm.index(elem)]
[...]
return total_perms
但我不知道如何完成第二个功能。
所以简而言之,我想给我的函数一些要生成的排列,并且该函数应该给我那个排列数量,其中没有一个元素出现在同一位置上比其他元素多(一次,如果全部出现有一次,两次,如果都出现两次,等等)。
【问题讨论】:
-
到底是什么问题?你在哪方面苦苦挣扎?
-
@AMC 我不知道如何完成该功能,我正在考虑将每个看到用户的索引(来自所有以前的排列)放入字典中,然后检查是否有任何新排列用户是否已在该位置看到过,但这将非常昂贵,因此我的代码中的 [...] 部分。
标签: python permutation permute