Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python put into list

def problem(n):
    myList = []
    for i in range(2, n):
        if n % i == 0:
            myList.append(i)

    return myList

with this code I was wondering how you would get the factors for example 12 to print out as[[6,2],[3,4]] something like this dosnt have to be in same order thanks.

like image 363
kid prog Avatar asked Jul 03 '26 01:07

kid prog


2 Answers

This should work for you:

import math

def problem(n):
    myList = []
    for i in range(2, int(math.sqrt(n) + 1)):
        if n % i == 0:
            myList.append([i, int(n/i)])

    return myList

To get the factor pair, this divides n by i, if i is a factor, which will by i's pair.

example:

print(problem(12)) #output: [[2, 6], [3, 4]]
like image 87
gommb Avatar answered Jul 04 '26 14:07

gommb


Another way. Loop using range and check if is_integer

num = 12
set([tuple(sorted(j)) for j in [[i, int(num/i)] for i in range(2,num) if (num/i).is_integer()]]
)
#Output:
#{(2, 6), (3, 4)}
like image 39
Transhuman Avatar answered Jul 04 '26 14:07

Transhuman