Skip to main content
 首页 » 编程设计

Python:检查列表是否可以通过交换两个元素来排序,只允许交换一次

2025年02月15日10artech

在下面的代码中,我试图找出左侧是否有两个元素大于右侧元素,但这似乎对我的问题不起作用。有什么提示可以编写进一步的逻辑吗?我被困在这里。

交换.py

def swap(lst): 
    count = 0 
    for k in range(0, len(lst)-1): 
        if lst[k] > lst[k+1]: 
            count += 1 
    if int(count) == 2: 
        print "Swapped" 
    elif int(count) == 0: 
        print True 
    else: 
        print False 
 
 
if __name__ == "__main__": 
    swap([1,2,3,4,0]) 
    swap([6,4,2,5]) 
    swap([6,4,2,8]) 
    swap([1,4,5]) 

我对程序的预期输出-

[1,4,5] will return True 
[6,4,2,8] will return Swapped 
[6,4,2,5] will return False 

请您参考如下方法:

from itertools import combinations 
def is_swappable(lst): 
    s = sorted(lst) 
    for i, j in combinations(range(len(lst)), 2): 
        l = lst[:] 
        l[i], l[j] = l[j], l[i] 
        if l == s: 
            return True 
    return False 

这是一个非常天真的解决方案。尝试交换列表中的每一对,看看这是否会导致排序列表。