簡體   English   中英

使用遞歸查找列表中元素的索引

[英]Find index of element in a list using recursion

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

我需要幫助來實現這個 function 使用遞歸。 對遞歸的東西真的很陌生,所以任何建議都會有所幫助

請注意, L是一個列表。 v是一個值。

那個有效

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

但非常愚蠢(並且只有在值存在時才有效)

您可以添加if v not in L: return -1以使其適用於任何情況,但這更糟糕。

它真的必須是遞歸的嗎?

我認為這是家庭作業。

所以你需要了解遞歸。 下面是一個例子:

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

您需要從一個起點開始,在您的情況下,它可能是第 0 個元素。

您需要一個終點,它應該是length - 1或您找到元素的時間。

簡單的 if else 應該在這里做,修改后的倒計時版本如上。

還有一種方式:

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

    return rec(l,v,index+1)

為什么有人會為此編寫遞歸代碼?

>>> [1,2,4,8].index(4)
2
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)

*遠程解釋器重新初始化*

6

8

-999991

假設索引為 0,以下代碼將返回元素的索引(如果存在),如果元素不包含在列表中,則返回 -1:

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

這是它的尾遞歸版本:

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)

但是請注意,Python 沒有尾調用優化(至少據我所知沒有)。

使用二進制搜索查找元素第一次出現的遞歸解決方案是 -

def Binary_Search(l, val, low, high):
    if low > high:
        return -1
    mid = (low+high)//2
    if len(l) == 1:
        if l[0] == val:
            return 0
        return -1
    if l[mid] == val:
        if mid == 0 or l[mid-1] != l[mid]:
            return mid
        else:
            return Binary_Search(l, val, low, mid-1)
    elif l[mid] < val:
        return Binary_Search(l, val, mid+1, high)
    else:
        return Binary_Search(l, val, low, mid-1)
def fi(arr,x):
   if len(arr)==0:
        return -1
    elif arr[0]==x:
        return 0
    k= fi(arr[1:],x)
    if k== -1:
        return -1
    else:
        return k+1

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM