0

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.

3
  • And you're not actually using P anywhere. Commented Nov 17, 2013 at 20:14
  • return will immediately end the function and return the value as the only return value. So you are essentially stopping your loop there. You might want to make it a generator instead and use yield. Commented Nov 17, 2013 at 20:33
  • @poke I'm fairly sure that she/he wants to return the entire list. But this also made me think of yield/generators :p. Here's a good read on the subject if anyone's interested. Commented Nov 17, 2013 at 20:39

2 Answers 2

1

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']
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.