重构递归的“出现”函数

时间:2015-10-13 17:46:56

标签: python recursion

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

这是我的计算课中出现的一个额外问题(阅读主题标签)。我已经尝试过默认参数,修补我并计算了很多方法,但我无法得到它。你怎么可爱的人呢?

4 个答案:

答案 0 :(得分:0)

def recursive_count(target, nested_num_list):
    count = 0
    # Make sure there's still stuff left.
    if len(nested_num_list) is 0:
        return 0
    item = nested_num_list.pop(0)
    if type(item) == type([]):
        count += recursive_count(target, item)
    elif target == item:
        count += 1
    count += recursive_count(target, nested_num_list)
    return count

如果您不介意修改输入参数,您可以每次从列表中弹出第一个项目并将其传回。 编辑:添加了嵌套处理。

答案 1 :(得分:0)

我会写一个递归的flattener并使用它的输出。

def flattener(left, right):
    try:
        res = reduce(flattener, right, left)
    except TypeError:
        left.append(right)
        res = left
    return res

>>> nested_list = [[0], [1, [2, 3]], [4, 5], [6, [7], [8, 9]], 10, [[[[11]]]], [], 12]
>>> flattened_list = reduce(flattener, nested_list, [])
>>> flattened_list
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
Go on with flattened_list ...

编辑:所以你想要一个单一的功能,这里有一个没有isinstance的版本或明确的长度检查或索引,只有一个内联 - if

def countin(seq, predicate):
    try:
        iterseq = iter(seq)
    except TypeError:
        return 1 if predicate(seq) else 0
    try:
        head = iterseq.next()
    except StopIteration:
        return 0
    c = countin(head, predicate)
    c += countin(iterseq, predicate)
    return c

>>> count_in(nested_list, lambda x: x % 2 == 0)  # count all even numbers
7
>>> len(filter(lambda x: x % 2 == 0, reduce(flattener, nested_list, [])))
7

答案 2 :(得分:0)

这是Python 3的另一种方法(很容易转换为python 2)。不修改输入参数或使用其他功能(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

答案 3 :(得分:-1)

def recursive_count(target, nested_num_list):
    return (recursive_count(nested_num_list[1:]) + (target == nested_num_list[0])) if nested_num_list else 0