python - 为什么这个解决方案没有陷入无限循环?

标签 python arrays

我解决了 HackerRank 上的最小交换 2 数组挑战 ( https://www.hackerrank.com/challenges/minimum-swaps-2/problem )。我的解决方案对于较大的数组会超时,因此我回去重构代码。我想到了我的新解决方案,几乎在我提交后我就意识到它行不通。然而,它确实......完美,但我要疯狂地试图找出原因。至少,为什么它没有陷入无限的 while 循环中,反复来回交换两个数组值?除了显而易见的事情之外,假设它确实神奇地跳出了循环,如果我们正在寻找,在用于计算交换的条件下它怎么可能得到正确的答案>最少 交换次数?我在代码中的不同位置添加了打印语句,以尝试查看发生了什么并自己理解它,但它们只会增加困惑。有人能带我了解一下我荒谬的天才的逻辑吗?或者这是一个侥幸?

#!/bin/python3

import math
import os
import random
import re
import sys

# Complete the minimumSwaps function below.
def minimumSwaps(arr):
    swaps = 0

    for x in range(0, n - 1):
        while arr[x] != x + 1:
            arr[arr[x] - 1], arr[x] = arr[x], arr[arr[x] - 1]
            swaps += 1

    return swaps


if __name__ == '__main__':
    fptr = open(os.environ['OUTPUT_PATH'], 'w')

    n = int(input())

    arr = list(map(int, input().rstrip().split()))

    res = minimumSwaps(arr)

    fptr.write(str(res) + '\n')

    fptr.close()

最佳答案

如果您想按照您的步骤操作

                             list  swap_index_1  swap_index_2
0  [7, 9, 6, 4, 2, 5, 1, 3, 8, 0]           NaN           NaN
1  [1, 9, 6, 4, 2, 5, 7, 3, 8, 0]           0.0           0.0
2  [1, 8, 6, 4, 2, 5, 7, 3, 9, 0]           1.0           7.0
3  [1, 3, 6, 4, 2, 5, 7, 8, 9, 0]           1.0           2.0
4  [1, 6, 3, 4, 2, 5, 7, 8, 9, 0]           1.0           5.0
5  [1, 5, 3, 4, 2, 6, 7, 8, 9, 0]           1.0           4.0
6  [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]           1.0           1.0
<小时/>
from random import shuffle
import pandas as pd
steps = []


def log(arr, s1, s2):
    steps.append(dict(list=arr.copy(), swap_index_1=s1, swap_index_2=s2))


n = 10
arr = list(range(n))
shuffle(arr)

swaps = 0

log(arr, None, None)

for x in range(0, n - 1):
        while arr[x] != x + 1:
            arr[arr[x] - 1], arr[x] = arr[x], arr[arr[x] - 1]
            swaps += 1

            log(arr, x, arr[x] - 1)

steps = pd.DataFrame(steps)
print(steps)

关于python - 为什么这个解决方案没有陷入无限循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56568987/

相关文章:

arrays - 要从列表中添加或删除的 Golang 映射或结构

python - 基于字符串创建新列

python - 如何在函数中将列表转换为数组 - python?

python - OpenCV restorePose相机坐标系

python - 如何将用户给定的字符串转换成列表

javascript - 在单次迭代中对两个数组求和

C++:数组的构造函数/初始化器?

javascript - Ajax - 如何在成功函数中使用返回的数组

python - 获取 pandas DataFrame 中每个组的前 N ​​个最大行

java - boolean 数组值比较