Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List comprehension to find all multiples of each number in list less than a number

I'm trying to write a function that will find all numbers that are a multiple of at least one number in a list where the multiple is less than a certain number. Here's what I've 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) would return [2,3,4,6,8,9]. I'm a little unsure how to do this with the for loop inside of the list comprehension.

like image 284
TheStrangeQuark Avatar asked Jan 04 '23 19:01

TheStrangeQuark


2 Answers

You can use the Python any() function to check if there is at least one instance of a divider in MultArray:

def MultiplesUnderX(MultArray,X):

    return [i for i in range(X) if any(i % x == 0 for x in MultArray)]
like image 69
Ajax1234 Avatar answered Jan 16 '23 21:01

Ajax1234


You can use the Python built-in function any which returns True if the iterable passed in contains any truth-y values in combination with a conditional at the end of the list comprehension limiting the list to only elements that satisfy the any call.

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

Your desired output is shown as such:

multiples = [2, 3]
print get_multiples_under(multiples, 10)
# [2, 3, 4, 6, 8, 9]
like image 38
foslock Avatar answered Jan 16 '23 22:01

foslock