Solution: Disarium Number
Contents
Solution: Disarium Number#
Write a function that determines whether a number is a Disarium (True) or not (False).
Function definition#
def is_disarium(n):
total = 0
position = 1
for digit in str(n):
total = total + (int(digit)**position)
position = position + 1
# return True or False
return total == n
Using enumerate()
:
def is_disarium(n):
total = 0
for position, digit in enumerate(str(n), start=1):
total = total + (int(digit)**position)
# return True or False
return total == n
Using enumerate()
and list comprehension
:
def is_disarium(n):
return sum([int(digit)**position for position, digit in enumerate(str(n), start=1)]) == n
Testing#
Check if your function returns the expected value using the cell below.
import unittest
class UnitTests(unittest.TestCase):
def test_type(self):
self.assertEqual(type(is_disarium(10)), type(False), 'The function should return a boolean operator')
def test_true(self):
self.assertEqual(is_disarium(89), True, 'The function should return True for the value 89')
def test_false(self):
self.assertEqual(is_disarium(100), False, 'The function should return False for the value 100')
unittest.main(argv=[''], verbosity=2,exit=False)
test_false (__main__.UnitTests) ...
ok
test_true (__main__.UnitTests) ...
ok
test_type (__main__.UnitTests) ...
ok
----------------------------------------------------------------------
Ran 3 tests in 0.004s
OK
<unittest.main.TestProgram at 0x7f90700c0810>