简体   繁体   中英

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.

You can also create a new function getperm to get the permutation index from your generator:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM