how to get the ordinal number in list

Rustom Mody rustompmody at gmail.com
Sun Aug 10 13:34:24 EDT 2014


On Sunday, August 10, 2014 10:40:21 PM UTC+5:30, Roy Smith wrote:
>  Rustom Mody  wrote:

> > > They haven't figured out yet that the 
> > > first step to solving a problem is to decide what algorithms you're 
> > > going to use, and only then can you start translating that into code.  
> > > They need to be led in small steps towards basic knowledge.
> > [...]
> > In my view this is starting from the wrong end.
> > I do not need to know which kind of adder the hardware is implementing to
> > use +, which sorting algorithm to use sort, etc.

> Well, no, but if the problem is, "Find the 5 largest numbers in a list", 
> you might start solving the problem by thinking, "OK, first I'm going to 
> sort the list into descending order, then I'm going to take the first 
> five items from that"(*)  Only then would you get down to "OK, how do I 
> sort a list of numbers in this language", and "OK, how do I select the 
> first five items from a list in this language".  That's what I mean by 
> first you come up with an algorithm, then you implement it in code.

>>> l= [6,2,9,12,1,4]
>>> sorted(l,reverse=True)[:5]
[12, 9, 6, 4, 2]

No need to know how sorted works nor [:5]

Now you (or Steven) can call it abstract.

And yet its 
1. Actual running code in the interpreter
2. Its as close as one can get to a literal translation of your
   "Find the 5 largest numbers in a list"

Yeah the reverse=True is a fly in the ointment.

I can do

>>> sorted(l)[-5:]
[2, 4, 6, 9, 12]

But that's a bit arcane

In any case coming back to the point

All the above are clearer than loops+assignments and can be 
taught before them



More information about the Python-list mailing list