简体   繁体   中英

Finding multiples using recursion

Given 1 to 100 numbers, for multiples of 3 it should print "he" ,for multiples of 5 it should print "llo" ,for both multiples of 3 and 5 it should print "hello".

This is what I have:

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

How would I do this recursively?

Here is a general outline for doing simple recursive things in 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

Of course, this doesn't handle all possible recursive programs. However, it fits your case, and many others. You would call f(100) , 100 would be current_value , you check to see if you've gotten to the bottom yet, and if so, return the appropriate value up the call stack. If not, you create a new case, which, in your case, is the "decrement" logic normally handled by the "loop" construct. You then do things for the current case, and then call the function again on the new case. This repeated function calling is what makes it "recursive". If you don't have an "if then" at the beginning of the function to handle the base case, and somewhere in the function recall the function on a "smaller" value, you're probably going to have a bad time with recursion.

How about the code below?

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)

Base case is if current reaches last_num or the maximum number you'd like to check.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM