0

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
2
  • This is very strange code for Python. the for i in range() is unusual, as is the get(lst, i). Commented Apr 6, 2014 at 3:01
  • Instead of get(lst, i), I would just suggest list[i] Commented Apr 6, 2014 at 3:07

2 Answers 2

1

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)

Sign up to request clarification or add additional context in comments.

Comments

0

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)

1 Comment

Or just use the integer value of the boolean: return int(get(lst, 0) == value) + recount(lst[1:], value)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.