给出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")
我将如何递归执行此操作?
答案 0 :(得分:1)
以下是在python中执行简单递归操作的概述:
DispatchQueue.main.async{
loading.dismiss(animated: false) {
OperationQueue.main.addOperation {
alert(title: "How can I show this alert?")
}
}
}
当然,这不能处理所有可能的递归程序。但是,它适合您的情况,还有许多其他情况。您将调用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
,然后检查是否已经触底,如果是,则在调用堆栈中返回适当的值。如果不是,则创建一个新案例,在您的案例中,这是通常由“循环”构造处理的“减量”逻辑。然后,您针对当前案例执行操作,然后在新案例上再次调用该函数。这种重复的函数调用使其成为“递归的”。如果在函数的开头没有“ if then”来处理基本情况,并且在函数的某处以“较小”的值调用该函数,则递归的时间可能会很糟糕
答案 1 :(得分:1)
下面的代码怎么样?
current_value
基本情况是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
或您要检查的最大数量。