使用递归来反转列表,并使用python计算列表中元素的出现次数

时间:2013-04-28 05:33:52

标签: python list recursion count reverse

我正在尝试使用递归和列表,通过编写一个接受字符串的函数,将其拆分为一个列表,然后使用递归生成字符串的反转版本,并计算一个次数a搜索词出现在列表中。换句话说,如果用户输入“快速棕色狐狸”,并想知道该句中出现“鸭子”的频率,该程序将输出“狐狸棕快速”,其次是“鸭子是”发现(在这种情况下,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()

2 个答案:

答案 0 :(得分:0)

REVERSECOUNT都不会执行这些打印语句 - 在执行到return之前,它们始终为print

您可能希望从printREVERSE中移除无用的COUNT,并在main中打印其返回值:

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))

答案 1 :(得分: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)))