gpt4 book ai didi

改组 itertools.permutation(range(15)) 时出现 Python OOM 错误

转载 作者:太空宇宙 更新时间:2023-11-03 21:24:04 26 4
gpt4 key购买 nike

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

不幸的是,虽然 this answer 中的方法如果我迭代前 10 个排列,可以避免存储所有排列并对其进行洗牌时遇到的内存不足问题!使用 itertools.permutations 返回的迭代器进行排列,它们都将按顺序排列。对我来说,获得排列的随机抽样(没有重复)非常重要。

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

最佳答案

如果我没记错的话,你的情况下的排列基本上就是以一种没有数字重复的方式对列表进行洗牌,也许你可以这样做:

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]]

关于改组 itertools.permutation(range(15)) 时出现 Python OOM 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53982678/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com