This works for all whole numbers, without using the modulus operator.
def divisibility_by_3(x): x = abs(x) while x > 9: list_of_values = [int(d) for d in str(x)] x = sum(list_of_values) return x in [0, 3, 6, 9]
- def divisibility_by_3(x):
list_of_values = [int(d) for d in str(x)]summation = sum(list_of_values)if summation % 3 == 0:return Trueelse:return False- x = abs(x)
- while x > 9:
- list_of_values = [int(d) for d in str(x)]
- x = sum(list_of_values)
- return x in [0, 3, 6, 9]
# TODO: Replace examples and use TDD development by writing your own tests # These are some of the methods available: # test.expect(boolean, [optional] message) # test.assert_equals(actual, expected, [optional] message) # test.assert_not_equals(actual, expected, [optional] message) # You can use Test.describe and Test.it to write BDD style test groupings test.assert_equals(divisibility_by_3(454), False) test.assert_equals(divisibility_by_3(222), True) test.assert_equals(divisibility_by_3(10593), True) test.assert_equals(divisibility_by_3(-10593), True)
- # TODO: Replace examples and use TDD development by writing your own tests
- # These are some of the methods available:
- # test.expect(boolean, [optional] message)
- # test.assert_equals(actual, expected, [optional] message)
- # test.assert_not_equals(actual, expected, [optional] message)
- # You can use Test.describe and Test.it to write BDD style test groupings
- test.assert_equals(divisibility_by_3(454), False)
- test.assert_equals(divisibility_by_3(222), True)
test.assert_equals(divisibility_by_3(10593), True)- test.assert_equals(divisibility_by_3(10593), True)
- test.assert_equals(divisibility_by_3(-10593), True)