Hackbright Code Challenges

Recursive Index: Solution

Recursive Index: Solution

Problem

Recursive Index

Whiteboard

Medium

Challenge

Easier

Concepts

Recursion

Download

recursive-index-solution.zip


def recursive_index(needle, haystack):
    """Given list (haystack), return index (0-based) of needle in the list.

    Return None if needle is not in haystack.

    Do this with recursion. You MAY NOT USE A `for` OR `while` LOOP.
    """

    # START SOLUTION

    def _recursive_index(needle, haystack, start_at):

        # Check if not found (we've gone too far)
        if start_at == len(haystack):
            return None

        # Have we found it?
        if haystack[start_at] == needle:
            return start_at

        return _recursive_index(needle, haystack, start_at + 1)

    return _recursive_index(needle, haystack, 0)