Ad

To switch things up a little bit, find all the factors of any number x that are primes to the first power, and return it in a list.

Example: find_prime(56) will return [2, 7], not [2**3, 7].

Extra requirements:

  • If you cannot easily read your code, add comments.
  • Use only one function to retrieve the numbers.
  • Do not use any imported modules
# Pretty ineffiecent code below--see if you can make it better

def find_primes(x):
    
    # Checks to see if x is less than 2, and thus, has no prime factors.
    if x <= 1:
        return []
    
    # Creates a list of all the factors of x
    factors = [i for i in range(2, x + 1) if x % i == 0]
    
    # Creates a list of all the factors that are not prime
    bad_factors = []
    
    # Adds numbers to the list bad_factors
    for j in range(len(factors)):
        for k in range(2, int(factors[j]**0.5) + 1):
            if factors[j] % k == 0:
                bad_factors.append(factors[j])
    
    # Finally, we make a list of all the good factors by removing all the "bad" (non-prime) factors
    # from our original list of factors, leaving only the "good" (prime) factors.
    good_factors = []
    for l in range(len(factors)):
        if not factors[l] in bad_factors:
            good_factors.append(factors[l])
    
    return good_factors