Henry Perez
Henry Perez

Reputation: 3

Adding a indentation of each recursive call

I'm trying to write a recursive function using factorial. I think I have the code down but am having trouble with the indentation.

def factorial(number,step=0):
    step += 1 
    st = ""

    if number == 1:
        print("Step", step, ": %sreturn 1"%(st)
        return 1
    else:
        print("Step", step, ": %s%d*factorial(%d)"%(st,number,number-1))
        st = "\t"
        return number * factorial(number - 1, step)

Output:
Step 1 : 5*factorial(4)
Step 2 : 4*factorial(3)
Step 3 : 3*factorial(2)
Step 4 : 2*factorial(1)
Step 5 : return 1

The results I am needing are:

Step 1 : 5*factorial(4)
Step 2 :     4*factorial(3)
Step 3 :         3*factorial(2)
Step 4 :             2*factorial(1)
Step 5 :                 return 1

Upvotes: 0

Views: 445

Answers (1)

FLAK-ZOSO
FLAK-ZOSO

Reputation: 4088

You only have to remove

st = "\t"

otherwise each time the indentation will be the same.


Try this instead:

st = "\t" * step

so that you will have step indentation levels each time.

Upvotes: 2

Related Questions