can any one help figure this out using python?
Design a recursive function that accepts two arguments into the parameters x and y. The function should return the value of x times y. Assume that x and y will always be positive nonzero integers. Remember, multiplication开发者_开发问答 can be performed as repeated addition as follows: 8 x 7 = 8 + 8 + 8 + 8 + 8 + 8 + 8
def my(x,y):
if x==0:
return 0
else:
return x*mul(x,x-1)
assertEqual(my(8,7),56)
assertEqual(my(8,5),40)
assertEqual(my(8,2),16)
Here's some pseudo-code that should do the trick:
define mult(x,y):
if x is zero:
return zero
return y plus mult(x-1, y)
Now, because I've always thought that Python is an ideal pseudo-code language, that should be fairly easy to convert. The idea with recursion is to define an operation in terms of simpler operations and provide a terminating one.
In order to understand this, imagine what happens when x
is 3 and y
is 7.
First time in mult(3,7)
, x
is non-zero so the result is y
(= 7
) plus mult(2,7)
.
For mult(2,7)
: result is y
(= 7
) plus mult(1,7)
.
For mult(1,7)
: result is y
(= 7
) plus mult(0,7)
.
For mult(0,7)
: result is zero since x
is zero.
This gives you (7 + (7 + (7 + (0))))
or 21
, as expected.
精彩评论