改组itertools.permutation(range(15))时发生Python OOM错误

时间:2018-12-31 00:55:28

标签: python permutation

在15个中!数字1-15的可能排列,我需要选择10!他们是随机的。

不幸的是,尽管this answer中的方法避免了存储所有排列并重新排列它们时遇到的内存不足的问题,但是如果我对前10个进行迭代的话!使用itertools返回的迭代器进行排列。排列将按顺序排列。对我来说,获取排列的随机抽样(无重复)非常重要。

from itertools import permutations
from random import shuffle
from math import factorial

count=15
placements = list(permutations(range(count), count))
shuffle(placements)
for placement in placements[:factorial(10)]:
    // do something with placement

我尝试了以下操作,但不能保证它不会两次选择相同的排列:

from math import factorial
from random import sample

count=15
for notused in range(factorial(10)):
    placement = sample(range(count),count)
    \\ do something with placement

当前正在尝试基于this answer的以下方法:

from math import factorial
from random import sample

placements = set()
count = 15
cap = factorial(10)
while len(placements) < cap:
    placements.add(tuple(sample(range(count),count)))
for placement in placements:
    \\ do something with placement

1 个答案:

答案 0 :(得分:0)

如果我没记错的话,那么您的排列方式基本上就是以无数字重复的方式对列表进行改组,也许您可​​以这样做:

from random import shuffle
samps = []
count = 0
while count < 10:

    j = list(range(15))
    shuffle(j)
    if j not in samps:
        samps.append(j)
    count += 1

这给出了:

[[0, 11, 13, 14, 1, 9, 6, 4, 5, 3, 7, 10, 2, 12, 8],
 [10, 1, 9, 2, 4, 0, 13, 14, 5, 8, 12, 7, 11, 3, 6],
 [3, 13, 6, 4, 12, 5, 0, 2, 10, 7, 1, 8, 11, 9, 14],
 [1, 10, 13, 7, 11, 9, 8, 4, 14, 0, 12, 2, 3, 6, 5],
 [9, 8, 7, 11, 3, 10, 6, 5, 4, 0, 14, 12, 1, 13, 2],
 [3, 11, 6, 8, 1, 4, 12, 14, 7, 5, 13, 0, 10, 9, 2],
 [5, 13, 8, 3, 0, 9, 1, 4, 11, 12, 6, 14, 2, 10, 7],
 [11, 1, 0, 2, 13, 12, 14, 3, 6, 10, 9, 7, 4, 8, 5],
 [12, 10, 6, 7, 2, 13, 3, 0, 1, 8, 4, 11, 14, 5, 9],
 [2, 5, 7, 9, 4, 12, 14, 6, 3, 10, 8, 13, 11, 0, 1]]