[Tutor] which is better solution of the question

Wayne srilyk at gmail.com
Tue Jun 16 16:23:14 CEST 2009


On Tue, Jun 16, 2009 at 8: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)))
>
> *Ans. 2*
> new_values = sorted(values, reverse=True)
> new_items = [items[x] for x in map(values.index,new_values)]
>
>

I would use a dict to store the values: {1:'phone', 5:'apple', 2:'car',
7:'town'} - then you just use sorted(mydict.keys(), reverse=True) to access
them in a big-endian (most important) first, or without reverse if I wanted
the least important value. This assumes that you can't have two values of
the same weight, of course.

If you're looking for speed, I'd look at timeit:
http://docs.python.org/library/timeit.html

I don't know which is considered more pythonic, though, so I'm afraid I
can't be of much more help than that.

HTH,
Wayne
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20090616/3d6be7a6/attachment-0001.htm>


More information about the Tutor mailing list