Function to take the minimum of 3 numbers

Chris Angelico rosuav at gmail.com
Sun Oct 9 11:24:16 EDT 2016


On Mon, Oct 10, 2016 at 12:41 AM, BartC <bc at freeuk.com> wrote:
> 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.

You assume that all equal numbers are identical. (And I say "numbers"
only because the problem definition did. This code does not require
numbers necessarily.)

>>> min3(1, True, 1.0)
1
>>> min3(1.0, True, 1)
1.0
>>> min3(True, 1.0, 1)
True
>>> 1 == 1.0 == True
True

>>> x = 1.0
>>> y = 1.0
>>> z = 1.0
>>> min3(x, y, z) is x
True
>>> min3(x, y, z) is y
False
>>> min3(x, y, z) is z
False

Your function provably returns the first number if given equal
numbers. That stipulation is far from meaningless; it explicitly
permits any means of selection, as long as one of the input values is
returned. Thus, for instance, this must always be valid:

>>> assert min3(x, y, z) in (x, y, z)

So this solution would NOT be valid:

def min2(a, b):
    return (a+b)/2 - abs(a-b)/2
def min3(a, b, c):
    return min2(a, min2(b, c))

It's mathematically perfect but inappropriate to this challenge, as it
violates the given rule.

ChrisA



More information about the Python-list mailing list