Python 递归查找列表中的最低数字。
我为我的递归函数作业写了一些代码。我想在列表中找到最小的数字。为什么这个代码不起作用?例如,当我输入2、-99和110时,程序返回-99,但当我输入2,5、-9时,它返回2。我不明白是什么问题Python 递归查找列表中的最低数字。,python,function,recursion,Python,Function,Recursion,我为我的递归函数作业写了一些代码。我想在列表中找到最小的数字。为什么这个代码不起作用?例如,当我输入2、-99和110时,程序返回-99,但当我输入2,5、-9时,它返回2。我不明白是什么问题 def rcompare(numList): end=len(numList)-1 if(end==-1): return 0 else: if (end!=-1): swapped=-1 for i
def rcompare(numList):
end=len(numList)-1
if(end==-1):
return 0
else:
if (end!=-1):
swapped=-1
for i in range(0,end):
if (numList[i]>numList[i+1]):
numList[i],numList[i+1]=numList[i+1],numList[i]
swapped=i
end=swapped
return numList[0]
numList=input("Please enter some numbers seperated by comma: ").split(",")
numList=[int(i) for i in numList]
print(rcompare(numList))
input()
首先,函数不是递归的 它不能正常工作的主要原因是它总是返回
numList[0]
和numList[1]
中较小的一个(仔细想想,只有循环的第一次迭代才能影响整体结果)
如果最小的值位于列表的较低位置,则函数将永远不会返回它。我将这样做
def lowest(l, low=None):
if low == None:
low = l[0]
if l:
if l[0] < low:
low = l[0]
del l[0]
return lowest(l, low=low)
else:
return low
print lowest([2,-99,110])
print lowest([2,5,-9])
def最低(l,低=无):
如果低==无:
低=l[0]
如果l:
如果l[0]<低:
低=l[0]
德尔l[0]
返回最低值(l,低=低)
其他:
低回报
打印最低值([2,-99110])
打印最低值([2,5,-9])
约翰西希的代码正确。失败的原因是您的代码比较了当前项和下一项,如果下一项较小,则交换这些项。这并不能保证最小的项目在列表中排在第一位。当[2,5,-9]的代码完成时,最后的列表是:[2,-9,5]。因此,如果最小值为numList[2]或更高版本,盲目依赖numList[0]将失败
如果您真的只想返回numList[0],那么您需要一个类似以下内容的循环:
for i in range(0,end):
if (numList[0]>numList[i]):
numList[0],numList[i]=numList[i],numList[0]
swapped=i
end=swapped
return numList[0]
此函数不是递归函数,它从不使用。@gecco此标记已弃用,请不要将其添加到新问题中。有关详细信息,请参阅标记wiki和链接在此处的meta post。@Servy感谢您的更新。值得注意的是,这具有二次复杂性(并且会破坏列表)。正如NPE指出的,除了对递归的学术理解之外,此函数没有用。如果您真的对更高效的排序算法感兴趣,请查看,快速排序也是递归的。