python - 为什么这个解决方案没有陷入无限循环?
问题描述
我解决了 HackerRank ( https://www.hackerrank.com/challenges/minimum-swaps-2/problem ) 上的 Minimum Swaps 2 数组挑战。我的解决方案会因更大的数组而超时,所以我回去重构代码。我想到了我的新解决方案,我几乎一提交就意识到它行不通。然而,它确实......完美,但我要疯了试图找出原因。最起码,为什么它不会陷入一个无休止的 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)
推荐阅读
- amazon-cloudformation - 使用 cloudformation 安装 fail2ban
- java - 如何为读/写firebase创建类
- haskell - Haskell 无法推断类型(或类型级别的 Nat)等式,尽管已明确注释?
- powershell - powershell 联系方式 | fl 结果排序
- jquery - 由于 VueJS,模态不会使用 jQuery 关闭
- ios - IOS Swift 4 隐藏键盘,同时点击周围干扰按钮按下
- r - 如何遍历列表并在 R 中创建单独的数据框
- coq - 证明函数应用在两个等价函数上的相等性
- php - PHP 将数字截断为最多 15 位,以实现与 MS Excel 中相似的精度
- c++ - 是否会为非类型模板参数的不同值实例化新类