2

Here's my python code

def search(myList, number):
    for i in myList:
        if i[0] == number:
            return i[1]
    return None

myList = [(5107261, 'Ernst'), (6524256, 'Arvo')]

number = 5107261

print(search(myList, number))

Now I want to write it using recursion but I'm not sure how to do it. I need some pointers to help me get started.

1 Answer 1

3

When writing recursive code, you want to define a base case, and you want to define a method for making your problem smaller on every step. In this example, we are working with lists, so a good base case would be an empty list, []. If the list is empty, it makes sense to return None. In your recursive case, you want to do some work to make the problem smaller. In this case we can check one element, and if that element is not what we are searching for, we can call the function again on a smaller version of the list.

Our result is a function like this:

def searchR(myList, number): 
    if length(myList) == 0: return None
    elif myList[0][0] == number: return myList[0][1]
    else: return searchR(myList[1:], number)

There are 3 cases. Case 1 is our base case, where the length of the list is 0. Case 2 is our success case, where we found the the target of the search. Case 3 is where we make our recursive call. Notice how the first element is removed from the new list! If the first element isn't removed, the function will loop forever.

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

1 Comment

glad I can help!

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.