iSam
iSam

Reputation: 55

Most Divisors in Python

I want to write a function called find_integer_with_most_divisors that accepts a list of integers and returns the integer from the list that has the most divisors. In case of a tie, return the first item that has the most divisors.

For example:

if the list is: [8, 12, 18, 6]

In this list, 8 has four divisors which are: [1,2,4,8] ; 12 has six divisors which are: [1,2,3,4,6,12]; 18 has six divisors which are: [1,2,3,6,9,18] ; and 6 has four divisors which are: [1,2,3,6]. Notice that both 12 and 18 are tied for maximum number of divisors (both have 6 divisors). My function should return the first item with maximum number of divisors; so it should return: 12


Now I wrote bellow code for find division of each number, that are in list. Can any body help me to continue this function. Thanks.

def find_integer_with_most_divisors(input_list):
    for i in input_list:
        my_list = []
        for x in range(1,i+1):
            if i % x == 0:
                my_list.append(i)

Upvotes: 1

Views: 2368

Answers (4)

Abdou
Abdou

Reputation: 13274

Yet another flavor of solution that uses sorted:

def find_integer_with_most_divisors(input_list):

    def divisor_length(num):
        length = 0
        for i in range(1,num+1):
            if num % i == 0:
                length += 1
        return length
    return sorted(input_list, key=lambda x: divisor_length(x), reverse=True)[0]


print(find_integer_with_most_divisors([8,12,18,6])) 

12

Upvotes: 0

Stefan Pochmann
Stefan Pochmann

Reputation: 28606

Why not just use max with the number of divisors as key?

>>> max([8, 12, 18, 6], key=lambda n: sum(n%d == 0 for d in range(1, n+1)))
12

Upvotes: 1

KarolisR
KarolisR

Reputation: 626

You can create a list of the number of divisors in your function and then match the highest number in that list to your original list:

def find_integer_with_most_divisors(input_list):
    nr_divisors = []
    for i in input_list:
        my_list = []
        for x in range(1, i+1):
            if i % x == 0:
                my_list.append(x)
        nr_divisors.append(len(my_list))
    return input_list[nr_divisors.index(max(nr_divisors))]

a = [8, 12, 18, 6]

print find_integer_with_most_divisors(a)

returns

12

Upvotes: 2

zondo
zondo

Reputation: 20336

All you need to do is keep track of the number with the most so far. I also changed your creation of my_list to something a little simpler:

def find_integer_with_most_divisors(input_list):
    winning_list = []
    winning_number = None
    for i in input_list:
        my_list = [x for x in range(1, i + 1) if i % x == 0]
        if len(my_list) > len(winning_list):
            winning_list = my_list
            winning_number = i
    return winning_number

Upvotes: 0

Related Questions