用于查找最小数字及其位置的 for 循环示例:
def smallest(list):
smallest = 1000000
smallestposition=-1
for pos,value in enumerate(list):
if(value < smallest):
smallest = value
smallestposition = pos
return smallest,smallestposition
print smallest([23,444,222,111,56,7,45])
最佳答案
在递归函数中使用 enumerate()
是没有意义的,因为枚举是迭代,这是递归的“相反”。
该函数的递归版本可以是:
def smallest(lst, idx=0):
s = (lst[idx], idx)
if idx == len(lst) - 1:
return s
return min(s, smallest(lst, idx + 1))
关于python - 枚举可以用在递归中吗?这个例子的递归是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34720228/