Reputation: 1528
So I just finished a coding test yesterday and I'm a tad neurotic. I was asked to create a class or function to check if elements in a list were all divisible by a scalable list of elements. This is the best I could come up with and was wondering if this could be improved. Thanks! And to get in front of it, I deliberately used a partial instead of lambda. To me it is much cleaner, and allows for better code re-use. Plus, I think Guido strongly discourages the use of Lambda and advises people switch to partials.
from functools import partial
def is_divisible(mod_vals, num):
"""A partial that runs a number against the list of modulus arguments, returning a bool value"""
for mod in mod_vals:
if num%mod != 0:
return False
return True
def divisible_by_factor(*mod_vals):
"""Returns a list based off a scalable amount of modulus arguments, no range support currently"""
comparison_list = []
div_partial = partial(is_divisible, (mod_vals))
for i in range(1, 100):
if div_partial(num=i):
comparison_list.append(i)
return comparison_list
Upvotes: 0
Views: 877
Reputation: 8982
>>> def divisible_by_factor(mod_vals):
>>> return [i for i in range(1, 100) if all(i % j == 0 for j in mod_vals)]
>>> print divisible_by_factor([2, 3, 5])
[30, 60, 90]
For every i
test whether it's divisible by all provided values. Keep only values that pass this test.
Upvotes: 3