Function to determine list max without itertools

Cameron Simpson cs at cskk.id.au
Fri Apr 19 19:53:19 EDT 2019


On 19Apr2019 05:38, Dan Sommers <2QdxY4RzWzUUiLuE at potatochowder.com> wrote:
>On 4/19/19 4:01 AM, Sayth Renshaw wrote:
>>
>>>Now, what happens when the code is tested with various (different) 
>>>sets of test-data?
>>>(remember the last question from my previous msg!?)
>>>
>>It fails on any list entry that isn't a float or an int, giving a TypeError.
>
>What if the *first* entry isn't a float or an int?  For
>instance, what if the list is ['a', 'b', 'c']?  What about
>['a', 'b', 3]?

Maybe it doesn't matter. Consider: the notion of a maximum implies that 
all the items are comparable, otherwise you can't tell if one item is 
the max versus another.

Provided all elements are mutually comparable eg all numeric or all 
strings, his code is fine.

As soon as you want to mix values, you are making a _policy_ decision.  

Are mixed values ok at all? If not, his code is fine.

Should values all be mutually comparable, _except_ for some special 
values? Such as None or the values NaN float values?

Should failing comparisons be ignored? (In which case the first element 
might dictate the definition of a valid comparison.)

Should they raise an exception (which his code will, for free)?

All these questions are policy because the assume some greater context 
not provided in the problem definition.

Sayth has only one decision to make here:

Is the basic algorithm all that is required: assume all values are 
mutually comparable? In many situations that will do very well.

Or should the basic algorithm "handle" noncomparable values?

Unfortunately the meaning of "handle" might go several ways: at least 
the basic form alerts you to the fact that there are noncomparable 
values.

Personally, I'd go one of 2 paths:

- leave the code alone - it a simple and understandable and assumes 
  _nothing_ about the values other than comparableness

- provide a test for _expected_ incomparable values as an additional 
  argument and use it to filter out these: any other values which fail 
  to compare represent bad input, and the function _should_ fail

But for the latter Python already has a builtin filter() function which 
the caller could trivially use to pre-filter the input data, avoiding 
any need to pointlessly complicate the basic maximum function.

So I'd say Sayth has attained the target goal.

Cheers,
Cameron Simpson <cs at cskk.id.au>

Q: How does a hacker fix a function which doesn't work for all of the 
elements in its domain?
A: He changes the domain.
- Rich Wareham <rjw57 at hermes.cam.ac.uk>



More information about the Python-list mailing list