我试图编写一些代码,这些代码将通过列表运行,未排序,找到最小的数字,而不是将其移动到结果。它将执行此操作,直到未排序变为空。基本上,一个排序程序。
我是否正确地将findMin函数放在electSort函数的循环中?
如何获取返回值并将其附加到新列表?
unsorted = [4, -9, 10, 2, 3.7, -20, 0]
result = []
def findMin(l):
l = unsorted
if len(l) == 0:
return None
min = l[0]
for i in range (len(l)):
if l[i] < min:
min = l[i]
return min
def selectionSort():
for a in range (len(unsorted)):
findMin(l)
result.append(min)
print(result)
selectionSort()
答案 0 :(得分:0)
你只需要将它传递给append
函数,但你需要将列表作为参数传递给selectionSort
函数:
def selectionSort(l):
for a in range (len(l)):
result.append(findMin(l))
print(result)
但是你的函数仍有许多问题,你可以将它用作配方作为实现选择的更加pythonic方式:
递归选择排序:
def sel_sort_rec(seq, i):
if i==0: return
max_j = i
for j in range(i):
if seq[j] > seq[max_j]: max_j = j
seq[i], seq[max_j] = seq[max_j], seq[i]
sel_sort_rec(seq, i-1)
selectionsort :
def sel_sort(seq):
for i in range(len(seq)-1,0,-1):
max_j = i
for j in range(i):
if seq[j] > seq[max_j]: max_j = j
seq[i], seq[max_j] = seq[max_j], seq[i]
答案 1 :(得分:0)
如果您每次都找到min并将其放入新列表中,则需要在找到另一个最小值之前从原始列表中删除该min。删除列表中的功能按值删除。
def selectionSort():
for a in range (len(unsorted)):
min = findMin(unsorted)
result.append(min)
unsorted.remove(min)
print(result)
输出:
[-20, -9, 0, 2, 3.7, 4, 10]