Python Forum

Full Version: Multiplication Recursive Solution - What's Going On Inside the Code?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello. Here is a block of code my instructor gave us to understand. It returns 12. I ask you: In the commented section at the bottom, do I have the steps correct in describing what is happening inside the code? If not, would anybody mind correcting it? Pete


def mult(a,b):
    if b == 1:
        return a
    else:
        return a + mult(a,b-1)
print(mult(3,4))

"""
a+a*b-1
3+3*4-1=3=12
6+3*3-1=2=12
9+3*2-1=1=12
"""
code obviously no multiplication(*) involved, only addition (+)and substraction (-). below is how i described step by step whats happening inside the code, hope u get the point

'''
mult(3, 4) = 3 + mult(3, 3)
mult(3, 3) = 3 + mult(3, 2)
mult(3, 2) = 3 + mult(3, 1)
mult(3, 1) = 3

mult(3, 4) = 3 + (3 + mult(3, 2))
mult(3, 4) = 3 + (3 + (3 + mult(3, 1))
mult(3, 4) = 3 + (3 + (3 + (3))
mult(3, 4) = 12
'''