返回递归函数的问题

时间:2019-02-13 21:58:48

标签: python python-3.x recursion

word = ["cs", "is", "fun", "homework", "is", "sometimes", "fun",
"exams", "are", "not", "fun"].
 lst = ["fun", "is","not"]

def num(word,lst,sofar):
    if len(lst) == 0:
        return sofar
    elif lst[0] in word == False:
        return num(word, lst[1:],sofar)
    else:
        sofar = sofar +1
        return num(word,lst,sofar)

函数返回列表中第一个单词在列表单词中出现的次数,并将其返回为sofr

该函数应返回6,但返回0

4 个答案:

答案 0 :(得分:0)

您的逻辑中有wordlst掉头了。您的代码缩小了保存要查找内容的列表,而不是查找内容的列表。

修复:

def num(word,lst,sofar):
    if not word:
        return sofar

    # ternary to add or not to add 1 to sofar
    return num(word[1:], lst, sofar+ (1 if word[0] in lst else 0)) 


word = ["cs", "is","fun", "homework","is", "sometimes", "fun", "exams", "are", "not", "fun"] 
lst = ["fun", "is","not"]

print(num(word,lst,0))

如果可以的话,也可以使用普通的

def num(word,lst,sofar):
    if not word:
        return sofar

    if word[0] in lst:
        return num(word[1:], lst, sofar+1)
    else:
        return num(word[1:], lst, sofar)

答案 1 :(得分:0)

首先:您声明wordlst错误,应该相反。 第二:您无需if-else就可以做到 第三:摆脱沙发人

LST = [
    "cs", "is", "fun",
    "homework", "is", "sometimes", "fun",
    "exams", "are", "not", "fun"
]
WORD = ["fun", "is","not"]

def num(word, lst):
    if len(lst) == 0:
        return 0
    inc = 1 if lst[0] in word else 0
    return num(word, lst[1:]) + inc

print(num(WORD, LST))

答案 2 :(得分:0)

问题是找到单词时您没有移到列表中的下一个单词。

您还在迭代错误的列表(交换lstword)。

尝试一下:

def num(word, lst, sofar):
    if len(word) == 0:
        return sofar
    elif lst[0] in word == False:
        return num(word[1:], lst, sofar)
    else:
        sofar = sofar + 1
        return num(word[1:], lst, sofar)

print(num(word, lst, 0))

稍微干净一点的版本:

def num(searchList, looking_for, sofar=0):
    if len(searchList) == 0:
        return sofar
    elif searchList[0] in looking_for:
        return num(searchList[1:], looking_for, sofar +1 )
    else:
        return num(searchList[1:], looking_for, sofar)


count = num(word, lst)
print(count)

答案 3 :(得分:0)

关于递归,我倾向于保持简单性:

word = ["cs", "is", "fun", "homework", "is", "sometimes", "fun", "exams", "are", "not", "fun"]
lst = ["fun", "is", "not"]

def num(word, lst, sofar=0):
    if word:
        return num(word[1:], lst, sofar + (word[0] in lst))

    return sofar

print(num(word, lst))