Shakiib
Shakiib

Reputation: 57

how to count how many element changed its position in a list after sorting?

I want to print the count of numbers that have changed their position. My code:

def mysort(arr):
    count = 0
    for i in range(len(arr)): 
        min_value = i
        for j in range(i, len(arr)): 
            if arr[j] < arr[min_value]:
                min_value = j
                count += 1
        
        temp = arr[i] 
        arr[i] = arr[min_value] 
        arr[min_value] = temp 
    
    return count 

my_list = [4,2,3,1,6,5]
print(mysort(my_list))

My code is returning 3 as output but it should return 4. How can I fix it?

Upvotes: 1

Views: 1155

Answers (1)

Chris Tang
Chris Tang

Reputation: 574

To count the number of elements with positions changed, why not try:

def count_change(old, new):
    # assume old and new have the same length
    count = 0
    for x,y in zip(old, new):
        if x != y:
            count += 1
    return count

Your code actually counts the number of value swap

Upvotes: 1

Related Questions