枚举可以在递归中使用吗?这个例子的递归是什么?

2024-10-02 06:34:04 发布

您现在位置:Python中文网/ 问答频道 /正文

使用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])

Tags: inpos示例forreturnifvaluedef
1条回答
网友
1楼 · 发布于 2024-10-02 06:34:04

在递归函数中使用enumerate()是没有意义的,因为枚举是迭代的,这是递归的“相反”。在

此函数的递归版本可以是:

def smallest(lst, idx=0):
    s = (lst[idx], idx)
    if idx == len(lst) - 1:
        return s
    return min(s, smallest(lst, idx + 1))

相关问题 更多 >

    热门问题