[Tutor] which is better solution of the question

Kent Johnson kent37 at tds.net
Tue Jun 16 16:49:40 CEST 2009


On Tue, Jun 16, 2009 at 9:52 AM, Abhishek
Tiwari<tiwariabhishekin at gmail.com> wrote:
> Question :
> The first list contains some items, and the second list contains their value
> (higher is better).
>
> items = [apple, car, town, phone]
> values = [5, 2, 7, 1]
>
> Show how to sort the 'items' list based on the 'values' list so that you end
> up with the following two lists:
>
> items = [town, apple, car, phone]
> values = [7, 5, 2, 1]
>
> Ans. 1
>
> values, items = list(zip(*sorted(zip(values,items), reverse=True)))

I like this one though the list() is not needed.

> Ans. 2
> new_values = sorted(values, reverse=True)
> new_items = [items[x] for x in map(values.index,new_values)]

This will become slow (O(n*n)) if the lists are large because it has
to scan the values list for each entry in new_values.

If you don't really need the sorted values list, you can use
dictionary lookup to get keys:

In [5]: ranks = dict(zip(items, values))

In [6]: ranks
Out[6]: {'apple': 5, 'car': 2, 'phone': 1, 'town': 7}

In [8]: sorted(items, key=ranks.__getitem__, reverse=True)
Out[8]: ['town', 'apple', 'car', 'phone']

You could pull the sorted ranks from the dict or just sort values independently:

In [9]: new_values = [ ranks[item] for item in _8]

In [10]: new_values
Out[10]: [7, 5, 2, 1]

My guess is that the overhead of creating the dict and doing the
lookups will make this slower than your first version but that is just
a guess. timeit is your friend if speed is your metric.

How do you measure "better"? Speed, clarity, ...?

Kent


More information about the Tutor mailing list