search(l, key):

if len(l) == 0:
return False
elif l[0] == key:
return True
else:
return search(l[1:], key)

I was just wondering if there is any way that i can get rid of "elif" statement. The function is suppose to return False if the key is not in the list "l" and True if otherwise. (it has to be a recursive function though)

And plus...
How would I modify this function so that it returns the index of key in l instead of True? (it still returns False if key is not in l)


I am not very good with computer programming...please someone help me? It would be greatly appreciated. =)
Thanks!

Recommended Answers

All 7 Replies

Hi!

The first one without any if-elif:

def search(l, key):
    return key in l

For the second one, .index() is your friend ;)

def search(l, key):
    if key in l: return l.index(key)
    return False

EDIT: Oh sorry, I didn't see it had to be recursive.

def search(l, key, index=0):
    if l:
        if l[0] == key: return index
        return search(l[1:], key, index+1)
    return False

Regards, mawe

Is there anyway you can do the last code without adding the index=0 to the search function arguments?

Yes there is

def search(l, key):
    if l:
        if l[0] == key:
            return 0
        s = search(l[1:], key)
        if s is not False:
            return s + 1
    return False

However, the good way to do this is to use the builtin index function !

dumb question but...what does if l: do?

It checks to see if l is existant, if there are no elelments in l then it will return False because your key cant be in an empty list! Therefore avoiding any unwanted Exceptions! :)

BTW, the letter 'l' is a rather poor choice for a variable name, since it looks much like the number '1' on many editors. I have gotten in the habit to use 'mylist' or 'qq' for casual lists.

i need a recursive function to break a directory so that i can display the elements of the directory in the table.

l = {'key1':,'key2':}
return l.values()

i want to show ths directory to be seen in table

and i have to call this code in ZPT.
plz help

Editor's Note:
Please start you own properly titled thread with this question. Don't hijack a solved thread since most people will not look there.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.