0
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

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?

Cœur
  • 37,241
  • 25
  • 195
  • 267
pythonnoob
  • 19
  • 1
  • 7

4 Answers4

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

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.

  • your code returns less occurrences then it should given a nested list [1,2,3,[1,1,1],[1]]. For target "1" your code results in 1 occurrence when the right answer is 5. And no you can modify the hell out of em! haha – pythonnoob Oct 13 '15 at 18:14
  • Oh dang! Sorry, forgot it was on a tested loop. – Lyr Lunace Oct 13 '15 at 18:29
0

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:

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
Cong Ma
  • 10,692
  • 3
  • 31
  • 47
0

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
AChampion
  • 29,683
  • 4
  • 59
  • 75
-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
pppery
  • 3,731
  • 22
  • 33
  • 46