我如何优化此 python 代码以对大输入进行排序?

How can I optimize this python code for sorting large input?

我正在尝试解决 HackerRank 上的 this 问题,该问题要求您对整数列表进行排序,并找出一个数字移动了多少次才能按正确的升序排列(上下文中的贿赂的问题)。

我的代码通过了 12 个测试用例中的 8 个,但在输入过大并出现超时错误时失败。这似乎是 HackerRank 上的一个常见指标,表明代码对于手头的问题来说太慢了。那么有没有办法优化这段代码,让它在更大的数据集上运行得更快?

def minimum_bribes(queue):
"""Returns the minimum number of bribes people in a queue accepted."""

# Variable to keep track of bribes
bribes = 0

# Check if queue is too chaotic
for i in queue:
    index = queue.index(i)
    if i - index > 3:
        return "Too chaotic"

# Use a bubble sort to find number of bribes
for i in range(len(queue) - 1):
    for j in range(len(queue) - 1 - i):
        if queue[j] > queue[j + 1]:
            queue[j], queue[j + 1] = queue[j + 1], queue[j]
            bribes += 1

return bribes


# Number of test cases
t = int(input())
results = []

for _ in range(t):

    # Number of people
    n = int(input())
    # Final State of queue
    q = list(map(int, input().rstrip().split()))

    # Add bribe counts to results array
    results.append(minimum_bribes(q))

# Print results
for result in results:
    print(result)

我建议使用 while 循环来测试条件,如果在之前的迭代中没有交换,则不需要 运行 新的交换迭代。

def minimumBribes(queue): 

     for i in queue:
            index = queue.index(i)
            if (i - index) > 3:
            print("Too chaotic")
            return    

    n = len(queue)
    swap =0
    swapped = True
    j =0    
    while swapped:
        j+=1
        swapped = False
        for i in range(n-j):
            if queue[i] > queue[i+1]:
                queue[i], queue[i+1] = queue[i+1], queue[i]
                swap +=1
                swapped = True

    print(swap)
    return swap