Search code examples
pythonmath

I am trying to gather all factors of a number, but am having an issue with isinstance


def factor(n):
    list_of_factors = []
    for number in range(1, n+1, 1):
        fraction = n / number
        if isinstance(fraction, int):
            list_of_factors.append(n)
            list_of_factors.append(-n)
    return list_of_factors

In this block of code, I am attempting to gather and return a list that contains all factors, positive and negative, of a certain input. However, I have an issue where the isinstance function isn't returning true even when the expression n / number is an integer. Is there something about isinstance that I'm missing?

I am aware of more optimized routes you could take. I currently am adding to the function to only loop through half of n, and if n / number is an integer, return n and n / number. Is there anything else I could add to make this more efficient?


Solution

  • Assuming n is an int:

    Division always returns a float. This is covered in the official Python tutorial here. You can think of a float as a rational number, and an integer divided by an integer is (by definition) a rational number (ℤ/ℤ ∈ ℝ), though floating-point numbers aren't arbitrarily-precise.

    To check if a float represents an integer, you can use float.is_integer(). However, for large numbers, rounding is an issue.

    The better way to check if a number is divisible by another is to use modulus:

    if n % number == 0:
    

    Lastly, you have a typo: you wrote n instead of number where you're appending to the list.

    So:

    def factor(n):
        list_of_factors = []
        for number in range(1, n+1):  # step=1 is the default
            if n % number == 0:
                list_of_factors.append(number)
                list_of_factors.append(-number)
        return list_of_factors
    

    Example:

    >>> factor(15)
    [1, -1, 3, -3, 5, -5, 15, -15]