Home > database >  Adding a indentation of each recursive call
Adding a indentation of each recursive call

Time:03-07

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

CodePudding user response:

You only have to change

st = "\t"

to

st  = "\t"

This will increase your indentation by one tab each time.

CodePudding user response:

change st = “\t” to st = “\t” st

  • Related