Search code examples
pythonif-statementquicksortmedian

python if elif different result


How can I find the median of the 1st, last and middle element and than swap the median with the 1st element?


Solution

  • If I'm reading your question correctly, you can do it like this:

    from numpy import median
    
    values    = [1,2,3,4,5,6]
    med       = median([values[0], values[len(values)/2], values[-1]]) # calculate median of first, middle and last element in the list
    values[0] = med # replace first element with median
    

    Which results in:

    >>> med
    4.0
    >>> values
    [4.0,2,3,4,5,6]
    

    This answers your question as written, but I'm not sure it's exactly what you want. You might try re-wording your question to make it a bit more clear exactly what you want the final output list to look like.

    Update

    As described in the comments, it appears swapping the value in the list equal to the median with the first element is the desired output. In that case, try the following:

    halfway_idx = len(values)/2
    med         = median([values[0], values[halfway_idx], values[-1]])
    if med == values[0]:
       pass # median already is in the first position
    elif med == values[halfway_idx]:
       values[0], values[halfway_idx] = values[halfway_idx], values[0] #swap middle and first
    else:
       values[0], values[-1] = values[-1], values[0] # swap first and last