Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Identifying the sequence in a recursive function

I need to identify the sequence order in the myst(n) function when it is called to then be able to give the output of myst(4). The function is defined as follow:

def myst(n):

    if n > 1:
        myst(n - 1)

        for i in range(n):
            print(n, end='')
        print()


myst(4)
OUTPUT

22
333
4444

But i can't understand why myst(4) gives this output, hence the misunderstanding of the sequence.

like image 789
Charles Lamarche Avatar asked Dec 30 '25 18:12

Charles Lamarche


1 Answers

Basically what is happening is that the function is recursing before it prints. So instead of printing 4444, then recursing, printing 333, etc., it recurses to the bottom-most level first, before printing the resuts. That means that the first call to the function that actually completes is the bottom-most one (the one that prints 22), then after that, the call producing the output 333 completes, until at last, the initial function call completes to print 4444.

like image 142
Ian Rehwinkel Avatar answered Jan 06 '26 02:01

Ian Rehwinkel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!