Solution: Factors#

Write a function that returns a list of all the factors (divisors) of a given integer number.

Function definition#

def get_factors(x):

    factors = []
    half = x // 2 # Floor operator - integer result

    for i in range(1, half + 1):
        if x % i == 0: # Modulus operator
            factors.append(i)

    factors.append(x)
    
    # return the factors list
    return factors

or using list comprehension:

def get_factors(x):

    factors = [i for i in range(1, x//2+1) if x%i==0]
    factors.append(x)
    
    # return the factors list
    return factors

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(get_factors(10)), type([10]), 'The function should return a list')
    def test_size(self):
        self.assertEqual(len(get_factors(100)), 9, 'The function should return a list with lenght=9')
    def test_result_odd(self):
        self.assertEqual(get_factors(101), [1, 101])
    def test_result_even(self):
        self.assertEqual(get_factors(200), [1, 2, 4, 5, 8, 10, 20, 25, 40, 50, 100, 200])

unittest.main(argv=[''], verbosity=2,exit=False)
test_result_even (__main__.UnitTests) ... 
ok
test_result_odd (__main__.UnitTests) ... 
ok
test_size (__main__.UnitTests) ... 
ok
test_type (__main__.UnitTests) ... 
ok

----------------------------------------------------------------------
Ran 4 tests in 0.005s

OK
<unittest.main.TestProgram at 0x7fc02e290b50>