3

Is it possible to convert the following loop:

c = 0
for a in find:
    c += 1
return c

Where find is a list like [a,b,c,d] to a function that uses recursion without using external libraries?

4
  • You need specifically a to be in the list? Or just some element in list? Commented Dec 6, 2017 at 9:58
  • just some element in list, I managed to do it! Commented Dec 6, 2017 at 9:59
  • It's strange to me that "without using external libraries" is emphasized here. This is a question of fundamental programming technique, and it seems very unlikely that any library would be helpful. Commented Dec 2, 2022 at 16:15
  • It is now more than clear to me. I was still a novice, now a PhD student in CS :) Commented Dec 2, 2022 at 20:04

3 Answers 3

1
def count(ls):
    if not ls:  # empty
        return 0
    return count(ls[1:]) + 1

Use it like this:

>>> find = [a, b, c, d]
>>> count(find)
4
Sign up to request clarification or add additional context in comments.

2 Comments

You should change to return count(ls[1:]) + 1, otherwise you'll get a RuntimeError: maximum recursion depth exceeded error. I didn't DV btw.
Yep, sorry, oversight.
0

I managed to do so by defining the following function:

def ric(find, n, c):    
    if n < len(find):
        if find[n] in find:
            c += 1
        n += 1
        return ric(find, n, c)
    else:
        return c

and calling it with ric(find, 0, 0)

Comments

0

Something as simple as this would work:

def to_rec(lst):
    # base case, when list is empty
    if not lst:
        return 0

    # recursive case
    return 1 + to_rec(lst[1:])

Base case: If the list has no elements, return 0.

Recursive case: Otherwise return 1 + the length of the list, minus one element, which is why we use [1:] here, to disregard the head of the list.

You could also explicitly set an accumulator with a helper function. If you've ever used a functional programming language, such as Haskell or Prolog, this technique is quite popular. Here is what it could look like:

# main function
def to_rec(lst):

    # calls helper function with starting accumulator of 0
    return accum(lst, 0)

def accum(lst, acc):

    # returns accumulator instead
    if not lst:
        return acc

    # increments accumulator, and looks at the tail of the list
    return accum(lst[1:], acc + 1)

Both work as follows:

>>> print(to_rec(['a', 'b', 'c', 'd']))
4
>>> print(to_rec([]))
0
>>> print(to_rec(['a']))
1

Comments

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.