Python Forum
Multiplication Recursive Solution - What's Going On Inside the Code?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Multiplication Recursive Solution - What's Going On Inside the Code?
#1
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
"""
Reply
#2
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
'''
swallow osama bin laden
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  with open context inside of a recursive function billykid999 1 580 May-23-2023, 02:37 AM
Last Post: deanhystad
  Multiplication Table code alexsendlegames100 3 1,374 Jun-06-2022, 09:45 AM
Last Post: Gribouillis
  Try to solve GTG multiplication table problem. Frankduc 6 2,014 Jan-18-2022, 08:26 PM
Last Post: Frankduc
  please looking for typo in my code (solution please) jamie_01 1 1,274 Jan-12-2022, 06:45 AM
Last Post: Gribouillis
  Need help with my Python code (Multiplication) NeedHelpPython 2 1,686 Oct-04-2021, 12:09 PM
Last Post: Pedroski55
  Newbie - code solution explained Stjude1982 2 1,844 Sep-16-2021, 08:54 AM
Last Post: Stjude1982
  Combine Two Recursive Functions To Create One Recursive Selection Sort Function Jeremy7 12 7,385 Jan-17-2021, 03:02 AM
Last Post: Jeremy7
  Quick Help - Timers - Need Small Solution for Working Code EwH006 5 4,043 Nov-17-2020, 04:09 AM
Last Post: EwH006
  List conversion and multiplication johnkyp 5 3,173 Jan-02-2020, 08:20 AM
Last Post: perfringo
  Matrix Multiplication Issue VIJENDRA 1 1,869 Dec-19-2019, 06:16 PM
Last Post: Gribouillis

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020