use*_*522 26 python permutation
我有一个27个元素的数组,我不想生成数组的所有排列(27!)我需要5000个随机选择的排列,任何提示将是有用的...
Mar*_*ers 36
要生成一个排列,请使用random.shuffle并存储结果的副本.在循环中重复此操作,每次检查重复(尽管可能不会有任何重复).一旦结果集中有5000个项目,请停止.
为了解决评论中的要点,Python的随机模块基于Mersenne Twister并且具有一段2**19937-1相当大的周期,27!因此它应该适合您的使用.
Pra*_*are 11
import random
perm_list = []
for i in range(5000):
temp = range(27)
random.shuffle(temp)
perm_list.append(temp)
print(perm_list)
Run Code Online (Sandbox Code Playgroud)
10888869450418352160768000000 我喜欢大数字!:)
和
10888869450418352160768000001 是PRIME !!
编辑:
#with duplicates check as suggested in the comment
perm_list = set()
while len(perm_list)<5000:
temp = range(27)
random.shuffle(temp)
perm_list.add(tuple(temp)) # `tuple` because `list`s are not hashable. right Beni?
print perm_list
Run Code Online (Sandbox Code Playgroud)
警告:如果RNG不好,这种情况永远不会停止!
itertools.permutations.它是一个生成器,因此它不会创建整个排列列表.你可以随机跳过,直到你有5000.
# apermindex should be a number between 0 and factorial(len(alist))
def perm_given_index(alist, apermindex):
for i in range(len(alist)-1):
apermindex, j = divmod(apermindex, len(alist)-i)
alist[i], alist[i+j] = alist[i+j], alist[i]
return alist
Run Code Online (Sandbox Code Playgroud)
用法: perm_given_index(['a','b','c'], 3)
这使用 Lehmer 代码进行排列作为j匹配的值。
| 归档时间: |
|
| 查看次数: |
30475 次 |
| 最近记录: |