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.
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)]
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With