Function to determine list max without itertools

DL Neil PythonList at DancesWithMice.info
Fri Apr 19 19:24:08 EDT 2019


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...

Upon opening a new module in one's text-editor/IDE one of the first 
steps should be to write an explanatory docstring. Similarly, after 
typing the letters "def" or "class"!

On the basis of this conversation, you might also benefit from reading 
about the use of doctests! (seeing we're talking docstrings - can always 
move to other test methods later)

I find this a useful habit, particularly if I am outlining an entire 
module or class, and only later coming back to flesh-out the code.

Further reading: Test-Driven Development


Of course all the comments in the world won't help if code != comment!!! 
Before congratulating ourselves that the code 'works': did you spot the 
difference in the better-developed 'English' description and the 
implementation in Python?


Regarding 'testing': Start with the scope and your objectives [as yet 
unstated, so we can only imagine what they might be]. When should it 
work, eg data-types. Why doesn't the code work with string data? Does it 
work if the list mixes different data-types? Should it work if a list 
element is itself a collection/class?

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 ]'?


Extension: if, instead of merely finding the largest value in the list 
(cf which element of the list is the largest!), what if the code also 
'moved' that element to the end of the list? Then, what if that function 
was called again but this time to operate on all of the list EXCEPT the 
last (which we already know is the largest) - and if this 'outer loop' 
were repeated 'len( list )' number of times (either by loop or (perhaps 
a later coding exercise) by recursion; what would be the final condition 
of the 'list'?

-- 
Regards =dn



More information about the Python-list mailing list