繁体   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