-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(puzzles): calculate product of x and y using recursion
- Loading branch information
BrianLusina
authored and
BrianLusina
committed
Nov 22, 2024
1 parent
6cbfd17
commit 3ff15c0
Showing
3 changed files
with
47 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,10 @@ | ||
# Product of Two Positive Integers | ||
|
||
Given two numbers, find their product using recursion. In Python, we usually use the * operator to multiply two numbers, | ||
but you have to use recursion to solve this challenge. | ||
|
||
Hint: | ||
|
||
```plain | ||
5 * 3 = 5 + 5 + 5 = 15 | ||
``` |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,14 @@ | ||
def recursive_multiply(x: int, y: int) -> int: | ||
"""Uses recursion to find the product of x and y | ||
Args: | ||
x (int): first number | ||
y (int): second number | ||
Returns: | ||
int: result of multiplication | ||
""" | ||
# this cuts down the recursive calls | ||
if x < y: | ||
return recursive_multiply(y, x) | ||
if y == 0: | ||
return 0 | ||
return x + recursive_multiply(x, y - 1) |
23 changes: 23 additions & 0 deletions
23
puzzles/product_of_two_positive_integers/test_recursive_multiply.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,23 @@ | ||
import unittest | ||
from . import recursive_multiply | ||
|
||
|
||
class RecursiveMultiplyTestCase(unittest.TestCase): | ||
def test_1(self): | ||
"""should return 15 from 5 and 3""" | ||
x = 5 | ||
y = 3 | ||
expected = x*y | ||
actual = recursive_multiply(x, y) | ||
self.assertEqual(expected, actual) | ||
|
||
def test_2(self): | ||
"""should return 1000000 from 500 and 2000""" | ||
x = 500 | ||
y = 2000 | ||
expected = x*y | ||
actual = recursive_multiply(x, y) | ||
self.assertEqual(expected, actual) | ||
|
||
if __name__ == '__main__': | ||
unittest.main() |