Alex
Alex

Reputation: 19

Create a minmax function that receives a list for argument and returns a tuple (min,max)

Important note: I can't use the min() and max() built-in function in my minmax function.

Here is the error found in my code:

expression « minmax([-1000, -999]) » doesn't have expected value
expected value : (-1000, -999)
actual value : (-1000, -1000)

Here is my code:

def minmax(liste):

    if len(liste)==1:
        return (liste[0],liste[0])

    elif len(liste)==0:
        return(None,None)

    else:

        min=liste[0]
        for i in liste:
            if i<min:
                min=i

        max=liste[0]
        for k in liste:
            if k>=max:
                max=k
                return(min,max)

Upvotes: 1

Views: 2605

Answers (2)

Eric Le Fort
Eric Le Fort

Reputation: 2691

Super late to this party but I couldn't pass up giving a better answer to this question. The above is very un-pythonic and so I thought I'd see what I could do to spruce it up (while maintaining the original signature and behaviour) while also making a couple slight optimizations:

def minmax(arr):
    """
    Given some array, returns a tuple containing the first occurrences of the minimum and maximum values.

    Args:
        arr (list of T): The list to search through
    Returns:
        A 2-tuple containing:
            lo (T): The minimum object in the array
            hi (T): The maximum object in the array
    """
    if not arr:  # This returns early if the array is None or []
        return (None, None)

    lo, hi = arr[0], arr[0]  # Don't use min/max, shadowing built-ins is bad form
    for val in arr:
        if val < lo:
            lo = val
        elif val > hi:
            hi = val

    return (lo, hi)

Upvotes: 1

hackfox code
hackfox code

Reputation: 529

change your last line code from:

for k in liste:
    if k>=max:
        max=k
        return(min,max)

Into:

for k in liste:
    if k>=max:
        max=k
return(min,max)

Because the return statement is in the for loop, it always returns the first element. You need to put the return statement outside to allow the loop to complete.

Upvotes: 2

Related Questions