重构递归“发生"功能 [英] Refactoring recursive "occurrences of" function

查看:63
本文介绍了重构递归“发生"功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

def recursive_count(target, nested_num_list):
    # This code finds all occurrences of "target" in "nested_num_list"
    # Rewrite this code without a while/for loop that achieves
    # the same results. Basically using only recursive calls and if's.

    count = 0
    i = 0
    while i < len(nested_num_list):
        if nested_num_list[i] == target:
            count += 1
        if type(nested_num_list[i]) == type([]):
            count += recursive_count(target, nested_num_list[i])    
        i += 1    
    return count

这是我的计算课上出现的一个额外问题(阅读主题标签).我试过默认参数,修改 i 并计算多种方法,但我无法得到它.你们可爱的人会怎么做?

This was a bonus question (read the hashtags) that came up in my computation class. I've tried default parameters, tinkering with i and count numerous ways but I cant get it. How would you lovely people go about it?

推荐答案

这是 Python 3 的另一种方法(很容易转换为 Python 2).不修改输入参数或使用其他函数(isinstance 除外):

Here's another approach for Python 3 (that is easily translated to python 2). No modification of input parameters or use of other functions (except isinstance):

def recursive_count(target, nested_num_list):
    if nested_num_list == []:
        return 0
    if isinstance(nested_num_list, int):
        return nested_num_list == target
    x, *y = nested_num_list
    # x, y = nested_num_list[0], nested_num_list[1:]  # Python 2
    return recursive_count(target, x) + recursive_count(target, y)

>>> recursive_count(1, [1,2,3,[1,1,1],[1]])
5

这篇关于重构递归“发生"功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆