kxjakkk
kxjakkk

Reputation: 7

Permutations of a list python

I need to define a function apply(L, P) where L is a list and P is a permutation, and it should return the list L o P. Assume len(L) = len(P)

What I've got so far is

import itertools 
def apply(L, P):
    for perm in L:
        return perm

An example of input is apply(['ah', 'boo', 'cc', 'du', 'eh'], [1, 4, 3, 2, 0]) But the only output from that is 'ah'

Any help would be great.

Upvotes: 0

Views: 319

Answers (2)

keyser
keyser

Reputation: 19189

Here's my version:

def apply(L, P):
    newL = [None]*len(L)
    for i,index in enumerate(P):
        newL[i] = L[index]
    return newL

This can easily be accomplished in one line in python, but I wanted to illustrate what's happening here.

The entire list is created before returning. return means that the function should exit and return the specified value. In your case that is 'ah' since it's the first element in the list you're looping through.

If you want to learn python, check out svk's very pythonic list comprehension.

Upvotes: 0

svk
svk

Reputation: 5919

This sounds like a task most easily achieved with a list comprehension:

>>> def apply(L, P):
...   return [ L[i] for i in P ]
... 
>>> apply(['ah', 'boo', 'cc', 'du', 'eh'], [1, 4, 3, 2, 0])
['boo', 'eh', 'du', 'cc', 'ah']

Upvotes: 1

Related Questions