在python中查找范围之间的最大除数?

时间:2013-12-13 11:36:54

标签: python python-2.7

我是python的新手,我给了两个数字,

a = 2
b = 9

a and b是包容性范围,即; (2,3,..,9)。我对最高离数的期望是6 and 8

解决方案说明:

 4 = 2 * 2(one factor)
 6 = 2 * 3(two factor)
 8 = 2 * 4(two factor)
 9 = 3 * 3(one factor)

所以,需要选择最多的因素。

如何从逻辑上列出python中除数的最大数量?。

实施例

如果我给出范围(1,2,..,10)。那么它应该给出最大除数的结果为6,8 and 10

依旧......

1 个答案:

答案 0 :(得分:0)

这也许就是你要找的东西:

import operator


def higest_divisors(a, b):
    _ret = {var: len([x for x in range(a, b+1) if not var % x]) for var in range(a, b+1)}.items()
    max = 0
    _to_ret = []
    for n, t in sorted(_ret, key=operator.itemgetter(1))[::-1]:
        if max <= t:
            _to_ret.append(n)
            max = t

    return _to_ret

if __name__ == '__main__':
    print higest_divisors(2, 10)

修改

这看起来好多了:

from itertools import takewhile
import operator


def highest_divisors(a, b):
    _divisors = sorted({var: len([x for x in range(a, b + 1) if not var % x])
                        for var in range(a, b + 1)}.iteritems(),
                       key=operator.itemgetter(1))[::-1]
    _max = _divisors[0][1]
    return [n for n, v in takewhile(lambda y: y[1] == _max, _divisors)]


if __name__ == '__main__':
    for var in highest_divisors(2, 10):
        print var