Janek Lass
Janek Lass

Reputation: 47

How to change this code to recursive code

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.

Upvotes: 2

Views: 59

Answers (1)

fileyfood500
fileyfood500

Reputation: 1321

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.

Upvotes: 3

Related Questions