Mariofan717
Mariofan717

Reputation: 57

Program to swap positions of items in list not working with all test cases

I'm writing a simple Python program that swaps the positions of the smallest and largest values in a user-inputted list. The code is as follows:

def swap_min_max(a_list): # a_list here is called formal parameter     
    min = 1
    max = 0
   
    for i in a_list:
        if i > max:
            max = i
        elif i < min:
            min = i
    
    for i in range(len(a_list)):
        if a_list[i] == max:
            a_list[i] = min

        elif a_list[i] == min:
            a_list[i] = max

a_list = [int(str_numbers) for str_numbers in input().split() ] # Input list creation via list comprehension
swap_min_max(a_list)
print(*a_list)

The code has no issues that I can identify, but it does not work with all test cases - for example, inputting 3 4 5 2 1 yields the desired output of 3 4 1 2 5, but inputting 20 50 10 30 70 40 yields 20 50 10 30 1 40 rather than the expected output of 20 50 70 30 10 40. Although I can see that this is related to my min and max variables at the beginning of the function definition, I'm unsure why this issue only arises in some cases.

Upvotes: 1

Views: 54

Answers (2)

1extralime
1extralime

Reputation: 626

def swap(alist):
    mx, max_idx = max(alist), alist.index(max(alist))
    mn, min_idx = min(alist), alist.index(min(alist))

    alist[min_idx] = mx
    alist[max_idx] = mn

    return alist
swap(a_list)

returns [20, 50, 70, 30, 10, 40]

Upvotes: 0

Bijan
Bijan

Reputation: 8606

min and max are built-in python functions. You can use these functions to find the minimum/maximum of a list, then get the index of the elements, and swap them.

def swap_min_max(a_list): # a_list here is called formal parameter     
    minVal = min(a_list)
    maxVal = max(a_list)
    
    minIndex = a_list.index(minVal)
    maxIndex = a_list.index(maxVal)
    
    a_list[minIndex], a_list[maxIndex] = a_list[maxIndex], a_list[minIndex]

   

a_list = [int(str_numbers) for str_numbers in input().split() ] # Input list creation via list comprehension

swap_min_max(a_list)
print(*a_list)

You can turn this into a messy one-liner with:

a_list[a_list.index(min(a_list))], a_list[a_list.index(max(a_list))] = a_list[a_list.index(max(a_list))], a_list[a_list.index(min(a_list))]

Input of 20 50 10 30 70 40

Returns 20 50 70 30 10 40

Upvotes: 1

Related Questions