The challenge
Your task is to create functionisDivideBy
(or is_divide_by
) to check if an integer number is divisible by each out of two arguments.
A few cases:
(-12, 2, -6) -> true
(-12, 2, -5) -> false
(45, 1, 6) -> false
(45, 5, 15) -> true
(4, 1, 4) -> true
(15, -5, 3) -> true
Test cases
Test.describe("Basic Tests")
Test.it("should pass basic tests")
Test.assert_equals(is_divide_by(-12, 2, -6), True)
Test.assert_equals(is_divide_by(-12, 2, -5), False)
Test.assert_equals(is_divide_by(45, 1, 6), False)
Test.assert_equals(is_divide_by(45, 5, 15), True)
Test.assert_equals(is_divide_by(4, 1, 4), True)
Test.assert_equals(is_divide_by(15, -5, 3), True)
Understanding how to solve this
To resolve this problem, we need to understand how to find if a number can be divided without a remainder in Python.
For this we will use Python’s modulo operator
, (%
):
10 % 5 # 0
# if we divide 10 by 5, there is no remainder
10 % 3 # 1
# if we divide 10 by 3, there is a remainder of `1`
Therefore, if we say 10 % 5 == 0
, the expression will equal True
, while the 10 % 3 == 0
will equal False. This is because there is a remainder of 1
in the second instance.
The solution in Python
Option 1:
def is_divide_by(number, a, b):
# if can divide without remainder
if number % a ==0 and number % b ==0:
return True
else:
return False
Option 2:
def is_divide_by(number, a, b):
return not (number%a or number%b)
Option 3:
def is_divide_by(n, a, b):
return n%a == 0 == n%b