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

标签 python python-2.7 recursion enumeration

用于查找最小数字及其位置的 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/

相关文章:

Python Apache Beam 端输入断言错误

python - 在 AppEngine 上支持多登录的最佳方式

python - 如何根据参数类型执行不同的操作

python - 如何从多个等长数组中删除相同的随机项?

python - 为什么列表理解中的元组需要括号?

python - Python 3.5+ 中的递归类型

python - 使用递归在 Python 中绘制分形树

Python requests.post 多部分/表单数据

python - matplotlib:箱线图对象中的传单设置不正确

ruby - 递归解决方案没有正确迭代