Find index of element in a list using recursion

余生颓废 提交于 2019-12-25 05:21:19

问题


def index(L,v)
    ''' Return index of value v in L '''
    pass

I need help with implementing this function using recursion. Really new to recursion stuff so any advice would help!

Note that L is a list. v is a value.


回答1:


That works

def recursive_index(L, v):
    return 0 if L[0] == v else 1 + recursive_index(L[1:], v)

but is pretty stupid (and will only work if the value exists)

You can add if v not in L: return -1 to make it work for any case, but that is even worst.

Do it really has to be recursive?




回答2:


Why would someone write recursive code for that??

>>> [1,2,4,8].index(4)
2



回答3:


I assume this is homework.

So you need to understand recursion. Here's an example:

def countdown(n):
    if n == 0:
        print "Hello World!"
    else:
        print n
        countdown(n-1)

You need to start with a starting point, in your case it would probably be the 0th element.

You need an end point, which should be the length - 1 or when you find the element.

Simple if else should do here, with a modified version of countdown as above.




回答4:


Yet another way:

def rec(l,v, index=0):
    try:
        if l[index] == v:
            return index
    except IndexError:
        return -1            

    return rec(l,v,index+1)



回答5:


L = [1, 2, 3, 4, 5, 6, 7, 11, 13]

def index(L, v):
    if len(L) == 0:
            return -1000000
    elif L[0] == v:
        return 0
    else:
        return 1 + index(L[1:], v)

print index(L, 7)
print index(L, 13)
print index(L, 100)

* Remote Interpreter Reinitialized *

6

8

-999991




回答6:


Assuming 0 indexing, the following code will return the index of the element if it exists, or -1 if it is not contained in the list:

def index(L, v):
    if L == []:
        return -1
    elif L[0] == v:
        return 0
    rv = index(L[1:], v)
    if rv < 0:
        return rv
    return rv + 1



回答7:


Here a tail recursive version of it:

def indexof(elem, list_):
    return indexof_tailrec(elem, list_, 0)

def indexof_tailrec(elem, list_, index):
    if index >= len(list_):
        return None
    if list_[index] == elem:
        return index
    return indexof_tailrec(elem, list_, index + 1)

Note, however, that Python does not have tail call optimization (at least not as far as I know).



来源:https://stackoverflow.com/questions/6481429/find-index-of-element-in-a-list-using-recursion

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!