What is the easiest way to get a list of whole factor pairs of a given integer?
For example: f(20)
would return [(1,20), (2,10), (4,5)]
.
def f(value):
factors = []
for i in range(1, int(value**0.5)+1):
if value % i == 0:
factors.append((i, value / i))
return factors
Or the same thing using a list comprehension:
def f(val):
return [(i, val / i) for i in range(1, int(val**0.5)+1) if val % i == 0]
Or this:
def f(n):
factors_list = []
for i in xrange(1, int(n**0.5) + 1):
if n % i == 0:
factors_list.append((i, n/i))
return factors_list
print f(20)
EDIT: Or in a one-liner using list comprehension:
def f(n):
return [(i, n / i) for i in xrange(1, int(n**0.5) + 1) if n % i == 0]
print f(36)
EDIT2: If you want the function to work for negative integers (as well as 0 and positive integers) use:
def f(n):
return [(i, n / i) for i in xrange(1, int(math.sqrt(math.fabs(n))) + 1) if n % i == 0]
print f(-36)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With