I'm a college student practicing some coding before school starts back up and I made a python function that is supposed to give the prime factorization of a number (excluding 1). It references a function that I made to check whether a number is prime, so I've included that function as well, although it shouldn't be important to the problem.
#Prime number checker
import math
def is_prime(n):
assert n >= 2
sqrt_n = math.ceil(math.sqrt(n))
last_digit = n % 10
#First, incorporate special cases
if last_digit == 0 or last_digit == 2 or last_digit == 4 or last_digit == 6 or last_digit == 8:
return False
#if the number is divisible by any of the prime numbers in this range, then it is not prime
if n > 5 and last_digit == 5:
return False
appropriate_list = [i for i in range(2, sqrt_n + 1)]
if any(n % i == 0 for i in appropriate_list):
return False
return True
#The integer factorization function
def integer_factorization(n):
factors_list = []
if is_prime(n) == True:
output_list = []
if factors_list:
output_list = [x for i in factors_list for x in i]
return output_list, n
else:
return n
else:
divisors_list = [2, 3, 5, 7]
for i in divisors_list:
if n % i == 0:
factors_list.append(i)
return integer_factorization(n // i), factors_list
My problem: I want the output to look normal, e.g. for the output of integer_factorization(20) to just be 5, 2, 2 in whatever order. Instead, the output looks like a series of lists within lists. E.g. integer_factorization(20) results in this: ((5, [2]), [2])
I am running these programs on Jupyter notebook.
Can anyone assist with this?
return output_list, n, and here:return integer_factorization(n // i), factors_list, if that isn't what you want, then don't return tuplesfactors_listis empty, sooutput_listwill also be empty. The loop that appends tofactors_listreturns immediately after the first recursive call, so it stops at the first prime factor.