kid prog
kid prog

Reputation: 35

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.

Upvotes: 3

Views: 191

Answers (4)

VPfB
VPfB

Reputation: 17247

In order to do the division only once:

for i in range(2, int(math.sqrt(n) + 1)):
    d, m = divmod(n, i)
    if m == 0:
        myList.append([i, d])

You will not get duplicates with upper limit sqrt(n)

Upvotes: 0

Sandeep Lade
Sandeep Lade

Reputation: 1943

You are almost correct . Using range you are not taking the number. Just add n+1 instead of n. That should work. Also you are not stroing the divident in the list. I added that too.

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

    return myList

Upvotes: 1

gommb
gommb

Reputation: 1117

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]]

Upvotes: 1

Transhuman
Transhuman

Reputation: 3547

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)}

Upvotes: 1

Related Questions