第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問(wèn)題,去搜搜看,總會(huì)有你想問(wèn)的

使用遞歸選擇偶數(shù)

使用遞歸選擇偶數(shù)

富國(guó)滬深 2021-08-14 16:02:34
這里我定義了一個(gè)函數(shù),它接受一個(gè)列表并返回同一個(gè)列表中偶數(shù)的計(jì)數(shù)。當(dāng)我運(yùn)行程序時(shí),我得到 None 作為回報(bào)。def count_even(lst, c = 0):    """    parameters : a lst of type list    returns : the even elements from that list    """    if lst == []:        return c    if lst[0] % 2 == 0:        c += 1    else:        return count_even(lst[1:])print(count_even([1,2,3,4,5,6,7,8,9]))我的問(wèn)題在哪里?
查看完整描述

3 回答

?
POPMUISE

TA貢獻(xiàn)1765條經(jīng)驗(yàn) 獲得超5個(gè)贊

當(dāng)前的實(shí)現(xiàn)有兩個(gè)基本問(wèn)題:

  1. c是 an int,并且ints 是不可變的。如果更改c,因此,這也并不意味著c在遞歸調(diào)用的“更新”,每次遞歸調(diào)用c將具有價(jià)值0; 和

  2. 如果第一項(xiàng)是偶數(shù),則不會(huì)返回值,因此None在這種情況下Python 將返回。


def count_even(lst, c = 0):

    if lst == []:

        return c

    if lst[0] % 2 == 0:

        c += 1

    # no else

    return count_even(lst[1:], c+1)  # pass a new value for c

然而,更緊湊的表示是:


def count_even(lst, c = 0):

    if not lst:

        return c

    return count_even(lst[1:], c + 1 - lst[0] % 2)

但是請(qǐng)注意,線性遞歸通常不是一個(gè)好主意,因?yàn)檎{(diào)用堆棧會(huì)隨著元素?cái)?shù)量的增加而增長(zhǎng),因此很容易導(dǎo)致溢出(尤其是因?yàn)?Python 沒(méi)有實(shí)現(xiàn)尾調(diào)用優(yōu)化 (TCO))。


查看完整回答
反對(duì) 回復(fù) 2021-08-14
?
繁花如伊

TA貢獻(xiàn)2012條經(jīng)驗(yàn) 獲得超12個(gè)贊

萬(wàn)一lst[0] % 2 == 0,您沒(méi)有返回任何內(nèi)容(因此隱式返回None)。您也永遠(yuǎn)不會(huì)c在遞歸中包含 的更新值。將其更改為


if lst == []:

    return c


if lst[0] % 2 == 0:

    c += 1


return count_even(lst[1:], c)

你很好。由于其他答案包括一些漂亮的替代解決方案,我將繼續(xù)提名


def count_even(lst):

    return 1 - lst[0]%2 + count_even(lst[1:]) if lst else 0

以及。


查看完整回答
反對(duì) 回復(fù) 2021-08-14
?
海綿寶寶撒

TA貢獻(xiàn)1809條經(jīng)驗(yàn) 獲得超8個(gè)贊

你幾乎做到了。只是一個(gè)簡(jiǎn)單的修正。您正在調(diào)用 else 塊中的遞歸,這是不正確的。您應(yīng)該在塊之外考慮它。檢查以下代碼:


def count_even(lst, c = 0):

    """

    parameters : a lst of type list

    returns : the even elements from that list

    """

    if lst == []:

        return c

    if lst[0] % 2 == 0:

        c = c + 1

    return c + count_even(lst[1:])



print(count_even([1,2,3,4,5,6,7,8,9]))



查看完整回答
反對(duì) 回復(fù) 2021-08-14
  • 3 回答
  • 0 關(guān)注
  • 194 瀏覽
慕課專欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購(gòu)課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)