Function to take the minimum of 3 numbers

Larry Hudson orgnut at yahoo.com
Sun Oct 9 16:46:10 EDT 2016


On 10/09/2016 05:01 AM, Cai Gengyang wrote:
>>>> def min3(a, b, c):
>     min3 = a
>     if b < min3:
>         min3 = b
>     if c < min3:
>         min3 = c
>         if b < c:
>             min3 = b
>     return min3
>
>>>> print(min3(4, 7, 5))
> 4
>

This is NOT a recommendation here, just a different way of looking at the problem (and is 
probably cheating anyway)...

def min3(a, b, c):
     return sorted([a, b, c])[0]  #  Create a list, sort it and return the 1st element

It can be extended to take any number of parameters:

def minn(*args):
     return sorted(args)[0]

The * syntax takes all the parameters and puts them into a single tuple.

This is _almost_ the same as the built-in min() function — the built-in requires a single 
(sequence) parameter, my minn() function requires multiple individual parameters.  (Both 
versions fail with zero parameters.)

-- 
      -=- Larry -=-



More information about the Python-list mailing list