python question?

can you explain to me how multiply(x-1,y)+y works for multiplying x and y? i really dont understand the +y part and the x-1 part kinda

Attachment image

2 Answers

Relevance
  • 3 weeks ago

    This is recursion.  We can show how this works by showing the stack.

    Let's do 5 * 4, which is 20.

    If we set x = 5 and y = 4.

    Check the if statements.  x isn't 0 so move on.  x isn't 1 so move on.

    So the next statement is a call back to itself calling (x - 1) and y, then add y to the answer:

    multiply(5, 4) = multiply(4, 4) + 4

    Loop again until x = 1 and we get:

    multiply(4, 4) = multiply(3, 4) + 4

    multiply(3, 4) = multiply(2, 4) + 4

    multiply(2, 4) = multiply(1, 4) + 4

    Now that x is 1, the return is y with no further recursion.  So the stack unwinds until the final answer is given:

    multiply(1, 4) = 4

    Now rewinding the stack, we get:

    multiply(2, 4) = multiply(1, 4) + 4 = 4 + 4 = 8

    multiply(3, 4) = multiply(2, 4) + 4 = 8 + 4 = 12

    multiply(4, 4) = multiply(3, 4) + 4 = 12 + 4 = 16

    multiply(5, 4) = multiply(4, 4) + 4 = 16 + 4 = 20

    So the final output is 20.

  • Chris
    Lv 7
    3 weeks ago

    This is recursion but I think that's incidental here.

    Your question seems to be mainly about the last line:

    return multiply(x-1, y) + y

    We could rewrite it like this:

    x_minus_one = x - 1

    product = multiply(x_minus_one, y)

    sum = product + y

    return sum

    Shouldn't be as intimidating now. "multiply(x-1, y) + y" is a so-called expression, and what the computer does it evaluate it step by step. It starts by subtracting 1 from the current value of x, then passes the result and y into the multiply function. This function returns the product, and the computer adds y to that, then returns the result.

    As for the other way this could be unclear:

    Take 15 times 23.

    That is 15 + 15 + 15 + 15 + ... + 15 where there are 23 of those 15s.

    Same as (15 + 15 + 15 + 15 + ...) + 15, where there are again 23 in total.

    That is the same as 15 times 22, plus 15.

    Which is the same as 23 times 15, which is 23 times 14, plus 23.

    In other words, 23 times (15 - 1), plus 23. Or (x - 1) * y + y.

Still have questions? Get your answers by asking now.