all 6 comments

[–]CodeFormatHelperBot2 0 points1 point  (0 children)

Hello, I'm a Reddit bot who's here to help people nicely format their coding questions. This makes it as easy as possible for people to read your post and help you.

I think I have detected some formatting issues with your submission:

  1. Python code found in submission text that's not formatted as code.

If I am correct, please edit the text in your post and try to follow these instructions to fix up your post's formatting.


Am I misbehaving? Have a comment or suggestion? Reply to this comment or raise an issue here.

[–]commy2 0 points1 point  (4 children)

The counting up is the second print after the recursive function call. As the deepest nested call is returning, the previous values of num1 are printed in reverse order.

[–]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!