views:

98

answers:

3

I'll to explain this right:
I'm in an environment where I can't use python built-in functions (like 'sorted', 'set'), can't declare methods, can't make conditions (if), and can't make loops, except for:

  • can call methods (but just one each time, and saving returns on another variable

    foo python:item.sort(); #foo variable takes the value that item.sort() returns

    bar python:foo.index(x);

  • and can do list comprehension

    [item['bla'] for item in foo]

...what I don't think that will help on this question

I have a 'correct_order' list, with this values:

correct_order = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

and I have a 'messed_order' list, with this values:

messed_order = [55, 1, 44, 3, 66, 5, 4, 7, 2, 9, 0, 10, 6, 8]

Well, I have to reorder the 'messed_order' list, using the index of 'correct_order' as base. The order of the rest of items not included in correct_order doesn't matter.

Something like this would solve (again, except that I can't use loops):

for item in correct_order:
    messed_order[messed_order.index(item)], messed_order[correct_order.index(item)] = messed_order[correct_order.index(item)], messed_order[messed_order.index(item)]

And would result on the 'ordered_list' that I want:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 55, 66, 44]

So, how can I do this?

For those who know zope/plone, I'm on a skin page (.pt), that doesn't have a helper python script (what I think that is not possible for skin pages, only for browser pages. If it is, show me how and I'll do it).

+1  A: 

It's hard to answer, not knowing exactly what's allowed and what's not. But how about this O(N^2) solution?

[x for x in correct_order if x in messed_order] + [x for x in messed_order if x not in correct_order]
Paul Hankin
@Paul I'll accept this, as I think anyone post another solution with a reduced cost. My list doesn't have too much items, so, I think I'm okay with this. But I continue looking for better solutions.
Gabriel L. Oliveira
A: 

Does the exact order of the 55/66/44 items matter, or do they just need to be listed at the end? If the order doesn't matter you could do this:

[i for i in correct_order if i in messed_order] +
    list(set(messed_order) - set(correct_order))
John Kugelman
@John I forgot to mention, doesn't matter. I'll just put Paul solution as he answered earlier (don't be mad with me).
Gabriel L. Oliveira
@John This solution is not valid as python built-in functions are not allowed.
Gabriel L. Oliveira
A: 

Here is one that destroys messed_order

[messed_order.remove(i) or i for i in correct_order if i in messed_order] + messed_order

This one sorts messed_order in place

messed_order.sort(key=(correct_order+messed_order).index)
gnibbler