Accounting list to find all the multiples of each number in the list less than the number

I am trying to write a function that will find all numbers that are multiples of at least one number in a list where the number of multiples is less than a certain number. Here is what I have tried so far:

def MultiplesUnderX(MultArray,X):
    '''
    Finds all the multiples of each value in MultArray that
    are below X.
    MultArray: List of ints that multiples are needed of
    X: Int that multiples will go up to
    '''
    return [i if (i % x == 0 for x in MultArray) else 0 for i in range(X)]

For example, MultiplesUnderX ([2,3], 10) will return [2,3,4,6,8,9]. I'm a little unsure how to do this with a for loop inside list comprehension.

+4
source share
3 answers

You can use the any () function of Python to check if at least one separator instance exists in MultArray:

def MultiplesUnderX(MultArray,X):

    return [i for i in range(X) if any(i % x == 0 for x in MultArray)]
+7
source

Python any, True, y , , any.

def get_multiples_under(factors, max):
    return [i for i in xrange(1, max) if any(i % factor == 0 for factor in factors)]

:

multiples = [2, 3]
print get_multiples_under(multiples, 10)
# [2, 3, 4, 6, 8, 9]
+1

Another version of this algorithm, which may be more efficient if the list is mostly co-prime, you can simply use range(i, X, i)to generate only multiples i, and then use heapq.mergeto combine iterators so that the returned iterator is sorted.

The last step is to remove duplicates during the game:

import heapq

def all_multiples(multi_list, max_N):
    gens = []
    for fac in sorted(set(multi_list)):
        # In Python 3 this is a generator of all multiples of "fac" less
        # than max_N. In Python 2 use xrange
        gens.append(range(fac, max_N, fac))

    # This will do a heap merge on the generators (which are already sorted)
    o = heapq.merge(*gens)
    last = None
    for val in o:
        if val != last:
            yield val
            last = val


if __name__ == "__main__":
    multi_list = [2, 4, 7]
    print(list(all_multiples(multi_list, 12)))
    # [2, 4, 6, 7, 8, 10]
0
source

Source: https://habr.com/ru/post/1680154/


All Articles