0

我正在尝试使用递归和列表来练习使用递归和列表,方法是编写一个函数,该函数接收一个字符串,将其拆分为一个列表,然后使用递归生成字符串的反转版本,并计算搜索词出现的次数在列表中。换句话说,如果用户输入“The quick brown fox”,并且想知道“duck”在这句话中出现的频率,程序会输出“fox brown quick The”,然后是“duck is找到(在本例中为 0)。看起来我的代码目前正在运行,但是,它不会打印出 REVERSE 和 COUNT 函数的结果。有人可以向我解释一下为什么吗?

此函数反转字符串中元素的顺序

def REVERSE(strng):
    new_list=''
#base case
    if len(strng)==0:
        return new_list+""
#recursive call
#returns the first element in the string, and adds it to the end of the rest of the string called recursively from the second element
    else:
        new_list+=REVERSE(strng[1:]) + strng[0]
        return new_list
    print (new_list)

计算字符串中子字符串出现次数的函数

def COUNT(strng,srch):
        count=0
    #base case
        if len(strng)==0:
            return count
    #recursive call in event search term found in the first element of the list
        elif strng[0]==srch:
            count+=1
            return COUNT(strng[1:],srch)
    #recursive call in event search term not found in first element of list
        else:
            count+=0
            return COUNT(strng[1:],srch)   
        print ("The term" + srch + "occurs" + count + "times")

这是调用这两个函数的程序。我将它们保存在单独的文件中以练习导入等

from functions import *
def main():
        terms = input ("Enter the list of terms:\n").split(" ")
    query = input("Enter a query term:\n")
    print("List in reverse order:")
    REVERSE(terms)
    print()
    COUNT(terms, query)
main()
4

2 回答 2

0

到目前为止,在我看来,以下内容可能会对您有所帮助。

#!/usr/bin/python

def REVERSE(strng):
    new_list=''
    #base case
    if len(strng)==0:
        new_list+=""
    #recursive call
    #returns the first element in the string, and adds it to the end of the rest of the string called recursively from the second element
    else:
        new_list+=REVERSE(strng[1:]) + strng[0] + " "
    return new_list


def COUNT(strng,srch):
        count=0
        #base case
        if len(strng)==0:
            count = 0
        #recursive call in event search term found in the first element of the list
        elif strng[0]==srch:
            count+=1
            COUNT(strng[1:],srch)
        #recursive call in event search term not found in first element of list
        else:
            count+=0
            COUNT(strng[1:],srch)
        return count

if __name__ == '__main__':
    terms = input ("Enter the list of terms:\n").split(" ")
    query = input("Enter a query term:\n")
    print("List in reverse order: %s" % REVERSE(terms))
    print ("The term '%s' occurs %d times." % (query, COUNT(terms, query)))
于 2013-04-28T06:04:22.753 回答
0

两者REVERSECOUNT不会执行那些打印语句——它们总是return在执行到达prints 之前。

您可能希望从and中删除无用print的 s ,并在其中打印它们的返回值:REVERSECOUNTmain

def main():
terms = input ("Enter the list of terms:\n").split(" ")
query = input("Enter a query term:\n")
print("List in reverse order:")
print(REVERSE(terms))
print()
print(COUNT(terms, query))
于 2013-04-28T05:47:11.093 回答