Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find elements in a list of which all elements in another list are factors, using a list comprehension

I have a list of numbers from which I have extracted common factors of all these numbers. For example, from list b = [16, 32, 96], I have produced list_of_common_factors = [1, 8, 16, 2, 4].

I have another list of integers, a and I wish to extract the numbers from list_of_common_factors of which all elements of a are factors. So if a = [2, 4], then I should end up with [4, 8, 16], as these are the numbers in list_of_common_factors of which 2 and 4 are factors.

However, I am struggling to figure out how to implement this step in a list comprehension, even in pseudocode. It should look something like this: [x for x in list_of_common_factors if all elements of a are factors of x]. It's the if statement that I'm having trouble with because I believe it should contain a for loop, but I can't think of a concise way to write it.

I have managed to do it the long way, using a nested for loop and it looks like this:

between_two_lists = []
# Determine the factors in list_of_common_factors of which all elements of a are factors.
for factor in list_of_common_factors:
    # Check that all a[i] are factors of factor.
    """ Create a counter.
        For each factor, find whether a[i] is a factor of factor.
        Do this with a for loop up to len(a).
        If a[i] is a factor of factor, then increment the counter by 1.
        At the end of this for loop, check if the counter is equal to len(a).
        If they are equal to each other, then factor satisfies the problem requirements.
        Add factor to between_two_lists. """
    counter = 0
    for element in a:
        if factor % element == 0:
            counter += 1
    if counter == len(a):
        between_two_lists.append(factor)

between_two_lists is the list I am trying to produce by converting the above code into a list comprehension. How can I do that, if it is even possible?

like image 778
AkThao Avatar asked Feb 17 '19 13:02

AkThao


2 Answers

It is what you are looking for:

[x for x in list_of_common_factors if all(x % i==0 for i in a)]
like image 105
Mehrdad Pedramfar Avatar answered Sep 28 '22 17:09

Mehrdad Pedramfar


So basically, you need to have a function returning the factors from a list of numbers. This function would return a list. And then you simply need to find the intersection of both list. Since each factor is unique, I suggest to use a set implementation which will be more efficient. To resume, the code would look like:

A = set(factors(#Input 1))
B = set(factors(#Input 2))
N = A.intersection(B)
like image 20
Mathieu Avatar answered Sep 28 '22 17:09

Mathieu