簡體   English   中英

使用遞歸查找倍數

[英]Finding multiples using recursion

給定1到100個數字,對於3的倍數,應打印“ he”;對於5的倍數,應打印“ llo”;對於3和5的倍數,應打印“ hello”。

這就是我所擁有的:

for i in range (1,100):
if(i%3==0):
    print("he")
elif(i%5==0):
    print("llo")
elif(i%3==0 and i%5==0):
    print("hello")

我將如何遞歸執行此操作?

這是在python中執行簡單遞歸操作的一般概述:

BASE_CASE = 1 #TODO

def f(current_case):
    if current_case == BASE_CASE:
        return #TODO: program logic here
    new_case = current_case - 2 #TODO: program logic here ("decrement" the current_case somehow)
    #TODO: even more program logic here
    return f(new_case) + 1 #TODO: program logic here

當然,這不能處理所有可能的遞歸程序。 但是,它適合您的情況,還有許多其他情況。 您將調用f(100) ,其中100將是current_value ,請檢查是否已經觸底,如果是,則在調用堆棧中返回適當的值。 如果不是,則創建一個新案例,在您的案例中,這是通常由“循環”構造處理的“減量”邏輯。 然后,您針對當前案例執行操作,然后在新案例上再次調用該函數。 這種重復的函數調用使其成為“遞歸的”。 如果在函數的開頭沒有“ if then”來處理基本情況,並且在函數的某處以“較小”的值調用該函數,則遞歸的時間可能會很糟糕。

下面的代碼怎么樣?

def find_multiples(current, last_num=100):

    # Base Case
    if current > last_num:
        return

    result = ""

    if current % 3 == 0:
        result += "he"

    if current % 5 == 0:
        result += "llo"

    if result:
        print(f"{current}: {result}")

    find_multiples(current+1, last_num)

find_multiples(1)

基本情況是current達到last_num或您要檢查的最大值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM