[英]Indexing a list of permutations in Python
This code generates the list of all permutations: 这段代码生成所有排列的列表:
def permute(xs, low=0):
if low + 1 >= len(xs):
yield xs
else:
for p in permute(xs, low + 1):
yield p
for i in range(low + 1, len(xs)):
xs[low], xs[i] = xs[i], xs[low]
for p in permute(xs, low + 1):
yield p
xs[low], xs[i] = xs[i], xs[low]
for p in permute(['A', 'B', 'C', 'D']):
print p
What I would like to do create an index for the list of permutations so that if I call a number I can access that particular permutation. 我想为排列列表创建一个索引,这样,如果我拨打电话号码,便可以访问该特定排列。
For example: 例如:
if index.value == 0:
print index.value # ['A','B','C','D']
elif index.value == 1:
print index.value # ['A','B','D','C']
#...
I am new to Python, thank you in advance for any guidance provided. 我是Python的新手,在此先感谢您提供的任何指导。
You can also create a new function getperm
to get the permutation index
from your generator: 您还可以创建一个新函数getperm
以从生成器中获取排列index
:
def getperm(index,generator):
aux=0
for j in generator:
if aux == index:
return j
else:
aux = aux +1
In: getperm(15,permute(['A', 'B', 'C', 'D']))
Out: ['C', 'A', 'D', 'B']
Iterators does not support "random access". 迭代器不支持“随机访问”。 You'll need to convert your result to list: 您需要将结果转换为列表:
perms = list(permute([....]))
perms[index]
Like levi said, it sounds like you want to use a dictionary. 就像莱维说的那样,听起来像您想使用字典。 The dictionary will look something like this: 该词典将如下所示:
#permDict = {0:['A', 'B', 'C', 'D'], 1:['A', 'B', 'D', 'C'], ...}
permDict = {}
index = 0
for p in permute(['A', 'B', 'C', 'D']):
permDict[index] = p
index += 1
Then just get a value according to the key you have assigned. 然后只需根据您分配的键获取一个值。
if index == 0:
print permDict[0] # ['A','B','C','D']
elif index == 1:
print permDict[1] # ['A','B','D','C']
#...
Or just store each permutation in a list and call those indices. 或者只是将每个排列存储在列表中,然后调用这些索引。
permList = [p for p in permute(['A', 'B', 'C', 'D'])]
#permList[0] = ['A', 'B', 'C', 'D']
#permlist[1] = ['A', 'B','D', 'C']
You can generate the desired permutation directly (without going through all previous permutations): 您可以直接生成所需的排列(无需遍历所有先前的排列):
from math import factorial
def permutation(xs, n):
"""
Return the n'th permutation of xs (counting from 0)
"""
xs = list(xs)
len_ = len(xs)
base = factorial(len_)
assert n < base, "n is too high ({} >= {})".format(n, base)
for i in range(len_ - 1):
base //= len_ - i
offset = n // base
if offset:
# rotate selected value into position
xs[i+1:i+offset+1], xs[i] = xs[i:i+offset], xs[i+offset]
n %= base
return xs
then 然后
>>> permutation(['A', 'B', 'C', 'D'], 15)
['C', 'B', 'D', 'A']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.