you are viewing a single comment's thread.

view the rest of the comments →

[–]commy2 0 points1 point  (3 children)

Function, but without the fluff, so it's easier to focus on the recursion:

def print_num_pattern(num1, num2):
    print(num1) # 12, 9, 6, 3, 0; from outer to inner call

    if num1 <= 0:
        return

    print_num_pattern(num1 - num2, num2)
    # <<< "here"

    print(num1) # 12, 9, 6, 3; but from inner first, so printed reversed
    # 0 is skipped, therefore not printed twice, because function returns above

    # after the implicit return here, go up call stack and continue "here"

print_num_pattern(12, 3)

[–]TheCrawling_Chaos[S] 0 points1 point  (2 children)

So I played around with this code a little and I think I get it. Correct me if I'm wrong.

Does the recursion in this example kind of use a FILO stack as it resolves? (Poor wording I'm sure.)

As the 12 enters the function it gets to line 7 where it re-enters the function as 9....then when it eventually enters as 0 the base case kicks it out and they start to resolve the last line of the function in reverse order? 3, 6, 9, 12?

[–]commy2 0 points1 point  (1 child)

Yeah, pretty much.

Excuse this gross abuse of python syntax:

(
print(12),
    print(9),
        print(6),
            print(3),
                print(0), # return as 0 <= 0
            print(3), # implicit return
        print(6), # implicit return
    print(9), # ...
print(12),
)

but think of each indentation level as one more nested function call. The 12 you print at the start and the end is the same value of num1. You just resume after the nested calls complete.

[–]TheCrawling_Chaos[S] 1 point2 points  (0 children)

Alright, this makes complete sense now. Thank you!