简体   繁体   中英

Most efficient way to check if numbers in a list is divisible by another number

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
>>> 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM