我正在尝试使用递归和列表来练习使用递归和列表,方法是编写一个函数,该函数接收一个字符串,将其拆分为一个列表,然后使用递归生成字符串的反转版本,并计算搜索词出现的次数在列表中。换句话说,如果用户输入“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()