user3404012
user3404012

Reputation: 27

Iteration to Recursion in Python

How can I write this function Recursively:

def count(lst, value):
    c = 0
    for i in range(lst.size):
        if get(lst,i) == value:# get(lst, i) is predefined. It gives me the value at i in lst
            c = c + 1
    return c

Upvotes: 0

Views: 114

Answers (2)

OrangeCube
OrangeCube

Reputation: 398

Seems you wanna count how many elements in lst is equal to value

IMHO, instead of doing this, you could get the count in just one short line:

lst.count(value)

Upvotes: 1

Ruben Bermudez
Ruben Bermudez

Reputation: 2333

This should make the trick:

def recount(lst, value):
    if len(lst) == 0:
        return 0
    if get(lst,0) == value:
        return 1 + recount(lst[1:],value)
    else:
        return recount(lst[1:], value)

Upvotes: 0

Related Questions