Function to determine list max without itertools

MRAB python at mrabarnett.plus.com
Fri Apr 19 20:34:00 EDT 2019


On 2019-04-20 00:24, DL Neil wrote:
> On 20/04/19 4:41 AM, Rob Gaddi wrote:
>> On 4/19/19 12:23 AM, Sayth Renshaw wrote:
>>> On Friday, 19 April 2019 17:01:33 UTC+10, Sayth Renshaw  wrote:
>>>> Set the first item in the list as the current largest.
>>>>          Compare each subsequent integer to the first.
>>>>                  if this element is larger, set integer.
>>>
>>> def maxitwo(listarg):
>>>      myMax = listarg[0]
>>>      for item in listarg:
>>>          if item > myMax:
>>>              myMax = item
>>>
>>>      return myMax
> 
>> When you understand what it is you intend to write (barring DL Neil's 
>> comments), and THEN write it, you write the correct thing.  Thus endith 
>> the lesson.
> 
> 
> +1, Rob's guidance saves time and embarrassment...
> 
[snip]
> Regarding 'optimisation': rather than 'disappearing' into high-volume
> and 'exotic' situations (see earlier comment), why not stick with the
> simple stuff? For example, once 'max' is initialised, is there a need to
> compare max with 'list[ 0 ]'?
> 
Is that really a problem?

How would you avoid comparing the initial max with list[0]? By slicing 
the list? By using 'iter' and 'next'? Do you expect that doing either of 
those to avoid a single comparison would make it faster? Is a comparison 
very expensive?

You could, of course, do some benchmarks to see if it makes a 
difference, but, personally, I'd just leave it.


More information about the Python-list mailing list