python - 使用递归计算列表中数字的出现次数

标签 python recursion

<分区>

我正在做的任务是:

Given an array of ints, compute recursively the number of times that the value 11 appears in the array. We'll use the convention of considering only the part of the array that begins at the given index. In this way, a recursive call can pass index+1 to move down the array.

我需要递归地执行此操作。我对此很陌生,但从技术上讲我做到了。 我有以下内容:

def array11(arr, index, cnt=0, num=0):
    if(cnt==len(arr)-index):
        print("yay!!! number 11 appears %d times"%num)
        return
    elif(arr[index:][cnt]==11): 
        num+=1
        cnt+=1
        array11(arr,index,cnt,num)
    else: 
        cnt+=1
        array11(arr,index,cnt,num)

但我觉得出于某种原因我通过添加具有默认值的“cnt”和“num”参数来实现它是一种廉价的方式。我只是不知道如何在没有计数器的情况下遍历“arr”数组!!

所以这是可以接受的?你会这样做吗?

提前致谢

最佳答案

您通常返回总计数:

def array11(arr, index):
    if index == len(arr):
        return 0
    return (arr[index] == 11) + array11(arr, index + 1)

我在这里使用了一些 Python 技巧,其中 boolint 的子类并且 True 等于 1。因此,添加up bool 值(或 bool 值和整数)导致 bool 值被解释为整数。

无论对 array11() 的最外层调用返回什么,您都可以使用 print

关于python - 使用递归计算列表中数字的出现次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24702955/

相关文章:

javascript - 如何通过 Django 中的确认弹出窗口创建“删除数据库中的项目”?

c - 使用递归时是否有最大重复次数?

recursion - 在函数定义中引用函数名称

powershell - 使用 if 条件递归重命名

python - 为什么用户信息不使用django附加到mysql数据库?

python - 基于wsdl创建pythonsoap服务器

python - 如何在 Mac 上安装 python 补丁

javascript - 使用递归 Javascript 的数组总和

c - C递归程序,打印所有乘以2的偶数,以及打印多少个数字

python - 注册为多用户