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.

kxjakkk
  • 7
  • 2
  • And you're not actually using P anywhere. – Sneftel Nov 17 '13 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`. – poke Nov 17 '13 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](http://stackoverflow.com/a/231855/645270) a good read on the subject if anyone's interested. – keyser Nov 17 '13 at 20:39

2 Answers2

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']
svk
  • 5,854
  • 17
  • 22
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.

keyser
  • 18,829
  • 16
  • 59
  • 101