我想将以下JAVA代码转换为python(我是Python的初学者)
public void selectionSort(int[] arr) {
int i, j, minIndex, tmp;
int n = arr.length;
for (i = 0; i < n - 1; i++) {
minIndex = i;
for (j = i + 1; j < n; j++)
if (arr[j] < arr[minIndex])
minIndex = j;
if (minIndex != i) {
tmp = arr[i];
arr[i] = arr[minIndex];
arr[minIndex] = tmp;
}
}
}
这是我写的,但它不起作用,我无法弄清楚我做错了什么
A = [86, 2,4 ,5, 6122, 87]
def selectionSort(a):
n = len(a)
print ("n = ", n)
for i in range (0, n-1):
minIndex = i
j = i+1
for j in range (0, n):
if(a[j] < a[minIndex]):
minIndex = j
if minIndex != i:
tmp = a[i]
a[i] = a[minIndex]
a[minIndex] = tmp
selectionSort(A)
print(A)
请帮我理解原因
答案 0 :(得分:2)
更改两行
j = i+1
for j in range (0, n):
到
for j in range (i+1, n):
匹配
for (j = i + 1; j < n; j++)
其他挑剔
在python中交换是优雅的
a[i], a[minIndex] = a[minIndex], a[i]
和整个块
minIndex = i
for j in range (i+1, n):
if(a[j] < a[minIndex]):
minIndex = j
if minIndex != i:
a[i], a[minIndex] = a[minIndex], a[i]
可以重构为
minIndex = min(range(i,n), key = partial(getitem, a))
a[i], a[minIndex] = a[minIndex], a[i]
为您导入partial from functools和getitem from operator
from functools import partial
from operator import getitem
所以你的最终版本看起来像
from functools import partial
from operator import getitem
def selectionSort(a):
n = len(a)
for i in range (n-1):
minIndex = min(range(i,n), key = partial(getitem, a))
a[i], a[minIndex] = a[minIndex], a[i]
看看最后会让你想知道将Java Code转换为Python作为练习确实是一种学习Python的好方法
答案 1 :(得分:0)
for j in range (0, n)
与使用i + 1启动的Java不同。
实现选择排序的更加pythonic方式可能如下所示:
A = [86, 2,4 ,5, 6122, 87]
def selectionSort(a):
# Go through all positions except the last one
# (that one will automatically be correct)
for index in range(len(a)-1):
value = a[index]
# enumerate all (index, value) pairs from the rest of the list
# and take the pair with the smallest value
min_subindex, min_value = min(enumerate(a[index+1:]), key=lambda x: x[1])
if min_value < value:
a[index] = min_value
a[min_subindex + index + 1] = value
selectionSort(A)
print(A) # [2, 4, 5, 86, 87, 6122]
答案 2 :(得分:0)
的问题:
j in range(0, n-1)
时,它会在0
而不是i+1
开始循环。使用
for j in range(i+1, n-1)
工作代码:
A = [86, 2,4 ,5, 6122, 87]
def selectionSort(a):
n = len(a)
print ("n = ", n)
for i in range (0, n-1):
minIndex = i
for j in range (i+1, n):
if(a[j] < a[minIndex]):
minIndex = j
if minIndex != i:
a[i], a[minIndex] = a[minIndex], a[i]
selectionSort(A)
print(A)