-3

I am new to python, I am giving two numbers,

a = 2
b = 9

a and b are inclusive range i.e; (2,3,..,9). and my expectation for highest number of divisors are 6 and 8.

Solution Explanation:

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

So, Need to Choose highest number of factors.

How to list the highest number of divisors in python from above logic ?.

Ex:

If I give the range (1,2,..,10). Then it should gave the result of highest number of divisors are 6,8 and 10.

and so on..

codeimplementer
  • 3,303
  • 2
  • 14
  • 16

1 Answers1

0

This perhaps is what you're looking for:

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)

EDIT

This looks a lot better:

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
Games Brainiac
  • 80,178
  • 33
  • 141
  • 199