2013-12-13 27 views
-3

我新的蟒蛇,我給兩個數字,在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

HTTP:/ /stackoverflow.com/questions/6800193/what-is-the-most-efficient-way-of-finding-all-the-factors-of-a-number-in-python –

+0

...和http://en.wikipedia.org/wiki/Integer_factorization –

+0

請清楚解釋問題。 – thefourtheye

回答

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 
+0

可怕的代碼,我知道,但它仍然是一項工作:P –

+1

認真?將變量命名爲「max」? ;) – thefourtheye

+0

@thefourtheye不是一個局部變量的完整災難:) – alko

相關問題