Divisible numbers comprehension with multiple terms
Write a function that receives a list of numbers and a list of terms and returns only the elements that are divisible by ALL the terms. You must use two nested list comprehensions to solve it.
divisible_numbers([12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1], [2, 3]) == [12, 6]
Warning, this assignment is difficult. If you get stuck, try working it with a for-loop first and then start turning it into list comprehensions.
Test Cases
test many divisible numbers - Run Test
def test_many_divisible_numbers():
result = divisible_numbers([12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1], [2, 3])
expected = [12, 6]
assert result == expected
test one divisible numbers - Run Test
def test_one_divisible_numbers():
result = divisible_numbers([16, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1], [2, 3, 4])
assert result == [12]
test both empty lists - Run Test
def test_both_empty_lists():
assert divisible_numbers([], []) == []
Solution 1
def divisible_numbers(a_list, terms):
return [x for x in a_list if len([1 for term in terms if x % term == 0]) == len(terms)]
Solution 2
def divisible_numbers(a_list, a_list_of_terms):
return [e for e in a_list if all([e % t == 0 for t in a_list_of_terms])]