【问题标题】:how to count how many element changed its position in a list after sorting?如何计算排序后有多少元素改变了它在列表中的位置?
【发布时间】:2020-09-21 03:26:55
【问题描述】:

我想打印改变位置的数字的数量。 我的代码:

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))

我的代码返回 3 作为输出,但它应该返回 4。我该如何解决?

【问题讨论】:

    标签: python-3.x list sorting


    【解决方案1】:

    要计算位置发生变化的元素数量,何不试试:

    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
    

    你的代码实际上计算了值交换的次数

    【讨论】:

    • sum(x != y for (x, y) in zip(old, new))
    • sum(map(operator.ne, old, new))
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多