Python 在解决名为Lily';家庭作业
问题的链接: 总结:我们必须找到将数组转换为排序数组所需的最小交换数。它可以按升序或降序排序。下面是我要排序的数组:Python 在解决名为Lily';家庭作业,python,arrays,algorithm,sorting,Python,Arrays,Algorithm,Sorting,问题的链接: 总结:我们必须找到将数组转换为排序数组所需的最小交换数。它可以按升序或降序排序。下面是我要排序的数组: arr = [3, 4, 2, 5, 1] 我们按升序排序,需要4次交换,降序时需要2次交换 对于下降:-交换5和3,然后交换3和2 现在,我已经编写了一个python代码来解决这个测试用例。代码如下: arr = [3, 4, 2, 5, 1] arr2 = arr[:] count = 0; count2 = 0; n = len(arr) registry = {}
arr = [3, 4, 2, 5, 1]
我们按升序排序,需要4次交换,降序时需要2次交换
对于下降:-交换5和3,然后交换3和2
现在,我已经编写了一个python代码来解决这个测试用例。代码如下:
arr = [3, 4, 2, 5, 1]
arr2 = arr[:]
count = 0; count2 = 0; n = len(arr)
registry = {}
for i in range(n):
registry[arr[i]] = i
sorted_arr = sorted(arr)
#######################first for loop starts#########################
#find no. of swap required when we sort arr is in ascending order.
for i in range(n-1):
if arr[i] != sorted_arr[i]:
index = registry[sorted_arr[i]]
registry[sorted_arr[i]],registry[arr[i]]= i, index
temp = arr[i]
arr[i],arr[index]=sorted_arr[i],temp
count = count + 1
###################first for loop ends#######################
# re-initalising registry and sorted_arr for descending problem.
registry = {}
for i in range(n):
registry[arr2[i]] = i
sorted_arr = sorted(arr2)
sorted_arr.reverse()
print(arr2) #unsorted array
print(registry) #dictionary which stores the index of the array arr2
print(sorted_arr) #array in descending order.
#find no. of swap required when array is in descending order.
for i in range(n-1):
print('For iteration i = %i' %i)
if arr2[i] != sorted_arr[i]:
print('\tTrue')
index = registry[sorted_arr[i]]
registry[sorted_arr[i]],registry[arr[i]]= i, index
temp = arr2[i]
arr2[i],arr2[index]=sorted_arr[i],temp
print('\t '+ str(arr2))
count2 = count2 + 1
else:
print('\tfalse')
print('\t '+ str(arr2))
print('######Result######')
print(arr)
print(count)
print(arr2)
print(count2)
问题是:
当我运行代码时,第二个for循环,即用于降序的for循环给出了错误的count值,即3。但是,当我对第一个for循环(即升序的for循环)进行注释时,它给出了正确的count值,即2
我想知道为什么当for循环1存在时for循环2会改变输出
循环1未注释时得到的输出
arr2: [3, 4, 2, 5, 1]
Registry: {3: 0, 4: 1, 2: 2, 5: 3, 1: 4}
sorted_arr: [5, 4, 3, 2, 1]
For iteration i = 0
True
[5, 4, 2, 3, 1]
For iteration i = 1
false
[5, 4, 2, 3, 1]
For iteration i = 2
True
[2, 4, 3, 3, 1]
For iteration i = 3
True
[2, 4, 3, 2, 1]
######Result######
[1, 2, 3, 4, 5]
4
[2, 4, 3, 2, 1]
3
错误在您的第二个循环中,您有:
registry[sorted_arr[i]],registry[arr[i]]= i, index
这应该是:
registry[sorted_arr[i]],registry[arr2[i]]= i, index
通常,使用这样的arr
和arr2
变量是个坏主意。而是生成两个函数,并将arr
作为参数传递给函数调用。然后,该函数应在对该数组进行变异之前创建该数组的本地副本([:]
)。所有其他变量都应该是函数的局部变量。这样,这两种算法使用各自的变量范围,不会有意外地将错误变量“泄漏”到另一种算法中的风险