简体   繁体   中英

How to make a list-search program in python using only recursion?

I am trying to make a python program ( using only recursion, no looping ) which takes a list of names from user and also a name to search for the list. The program has to tell whether the name exists in the given list or not. Additionally, if an element of the list is "James Christ" and we search for "James" , the program should return true. I have made half of the program. But my code doesn't perform the additional function. My code is like this:

L1=list(input("Enter the list of names : "))
x=input("Enter the name to search : ")

def search(L1,x):
    if len(L1)==0:
        return "Not found!!"
    else:
        if x==L1.pop(0):
         return "Entry found!!"
        else:
         return search(L1,x)

print search(L1,x)

Please, help me out!

This is a solution without destroying the original list.

montys = [
    'John Cleese', 'Graham Chapman', 'Terry Gilliam',
    'Eric Idle', 'Terry Jones', 'Michael Palin']
actor = 'Idle'


def search(data, word):
    if len(data) == 0:
        return "Not found!"
    else:
        if word in data[0]:
            return "Entry found!"
        else:
            return search(data[1:], word)

print(search(montys, actor))

For more information see Junuxx answer.

Instead of if x==L1.pop(0) , use if x in L1.pop(0) .

This will work for James and James Christ , but also for Jamesy Bob or SuperJames .

To make sure that the input matches an entire word of the name in the list, you could do if x in L1.pop(0).split() . This works by splitting James Christ into a list of words ( ['James', 'Christ'] ) and checking if 'James' occurs as one of the words in that list.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM