3

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.

3 Answers3

1

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.

Ian Rehwinkel
  • 2,486
  • 5
  • 22
  • 56
1

In your question, you are recursing before you print, the call order will be
myst(2) -> myst(3) -> myst(4)

But if you print and then recurse, the call order will change to
myst(4) -> myst(3) -> myst(2), as below.

def myst(n):

    if n > 1:

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


myst(4)
#4444
#333
#22
Devesh Kumar Singh
  • 20,259
  • 5
  • 21
  • 40
0

When you call myst(x), you firstly start to calling myst(x-1) and AFTER it ends you continue to myst(x). So you call it to the myst(2) and then start to process another mysts. If you want to print it firstly, you should move recursive calling to the bottom:

def myst(n):
    if n > 1:
        for i in range(n):
            print(n, end='')
        print()
        myst(n - 1)

myst(4)
4444
333
22
vurmux
  • 9,420
  • 3
  • 25
  • 45