clueless
clueless

Reputation: 3

How can I turn the result of this code into a list or a set?

How can I turn the result of this code into a list or a set?

def factors(x):
    for i in range(1, x + 1):
        if x % i == 0:
            print(i)

num = 100
factors(num)

Upvotes: 0

Views: 45

Answers (2)

Sidmeister
Sidmeister

Reputation: 856

Check the divisibility till the square root of the value. If matches, add divisor and quotient to the factors list. Then create a set out of the list to remove repeated elements (which will only arise if x is a square of an integer). Finally return the list after sorting it so that the returned list is in ascending order.

import math
def factors(x):
    f = []
    for i in range(1, math.ceil(math.sqrt(x))+1):
        if x % i == 0:
            f.append(i)
            f.append(x/i)
    return sorted(set(f))

Upvotes: 0

Martijn Pieters
Martijn Pieters

Reputation: 1123240

You need to return something rather than print. You can build a list in the function:

def factors(x):
    result = []
    for i in range(1, x + 1):
        if x % i == 0:
            result.append(i)
    return result

num = 100
print(factors(num))

You can make that a set too, if you want, using result = set() and result.add().

The other option is to turn the function into a generator; you'd have to do some iteration after calling the function:

def factors(x):
    for i in range(1, x + 1):
        if x % i == 0:
            yield i

num = 100
for factor in factors(num):
    print(factor)

but you can also 'pull in' all the values into a list or set:

factors_list = list(factors(num))
factors_set = set(factors(num))

Upvotes: 1

Related Questions