Check which numbers in the list are divisible by certain numbers?

Write a function that takes a list of numbers and a list of terms and returns only those items that are divisible by all of those terms. To solve the problem, you must use two nested lists.

divisible_numbers ([12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1], [2, 3]) # returns [12, 6]

def divisible_numbers (a_list, a_list_of_terms):

I have undefined pseudocode so far which consists of a checklist, check if it is divisible, if added to a new list, check the new list if divisible by the next term and repeats until you go through everything terms, I don't want anyone to do this for me, but perhaps a hint in the right direction?

+3


source to share


1 answer


The inner expression should check whether for a certain number this number will be evenly divisible by all members in the second list

all(i%j==0 for j in a_list_of_terms)

      

Then an external list comprehension to iterate over the elements of the first list

[i for i in a_list if all(i%j==0 for j in a_list_of_terms)]

      



Together

def divisible_numbers(a_list, a_list_of_terms):
    return [i for i in a_list if all(i%j==0 for j in a_list_of_terms)]

      

Testing

>>> divisible_numbers([12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1], [2, 3])
[12, 6]

      

+9


source







All Articles