Skip to content Skip to sidebar Skip to footer

Refactoring Recursive "occurrences Of" Function

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

Solution 1:

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):

defrecursive_count(target, nested_num_list):
    if nested_num_list == []:
        return0ifisinstance(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 2return recursive_count(target, x) + recursive_count(target, y)

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

Solution 2:

defrecursive_count(target, nested_num_list):
    count = 0# Make sure there's still stuff left.iflen(nested_num_list) is0:
        return0
    item = nested_num_list.pop(0)
    iftype(item) == type([]):
        count += recursive_count(target, item)
    elif target == item:
        count += 1
    count += recursive_count(target, nested_num_list)
    return count

If you don't mind modifying the input parameters, you can just pop the first item from the list every time and pass it back in. Edit: Added the nesting handling.

Solution 3:

I'd write a recursive flattener and use its output.

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 ...

Edit: So you want one single function that does this, and here's a version without isinstance or explicit length checking, or indexing, and with only one inline-if:

defcountin(seq, predicate):
    try:
        iterseq = iter(seq)
    except TypeError:
        return1if predicate(seq) else0try:
        head = iterseq.next()
    except StopIteration:
        return0
    c = countin(head, predicate)
    c += countin(iterseq, predicate)
    return c

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

Solution 4:

defrecursive_count(target, nested_num_list):
    return (recursive_count(nested_num_list[1:]) + (target == nested_num_list[0])) if nested_num_list else0

Post a Comment for "Refactoring Recursive "occurrences Of" Function"