Function to take the minimum of 3 numbers

BartC bc at freeuk.com
Sun Oct 9 09:41:29 EDT 2016


On 09/10/2016 13:01, Cai Gengyang wrote:
> I'm moving on to chapter 9 (http://programarcadegames.com/index.php?lang=en&chapter=lab_functions) of programarcadegames for the time being and going back to chapter 8 later (its just fucking frustrating and doesn't seem to work for the time being and I have a very bad temper).
>
> At least for chapter 9, I got the first part correct at first try --- define a function that takes and prints the smallest of 3 numbers. I pasted it here for reference and discussion. The code can also be further modified to include a clause that says that if two numbers tie for smallest, choose any of the two numbers. (I will attempt to do it and then post it here again for future discussion with users here
>
>
>>>> 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
>

The exercise says you must use an if/elif chain. The first thing that 
comes to mind is:

def min3(a,b,c):
     if a<=b and a<=c:
         return a
     elif b<=a and b<=c:
         return b
     else:
         return c

The bit about numbers tying for smallest is not meaningful; the caller 
can't tell if a minimum value of 42 came from a, b or c.

-- 
Bartc



More information about the Python-list mailing list