[英]Using recursion to reverse a list, and count the number of occurances of an element within the list, using python
我正在嘗試使用遞歸和列表,方法是編寫一個函數,該函數接受一個字符串,將其拆分為一個列表,然后使用遞歸生成字符串的反向版本,並計算搜索項出現的次數在列表中。 換句話說,如果用戶輸入“ 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()
REVERSE
和COUNT
都將永遠不會執行這些打印語句-它們將始終在執行到達print
之前return
。
您可能要從REVERSE
和COUNT
刪除無用的print
,並在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))
到目前為止,在我看來,以下內容可能會對您有所幫助。
#!/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)))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.