3
\$\begingroup\$

The following program is written in python. Is there a more efficient way to write this program? Suggestions and criticism are welcome. You can also comment about my variable naming practices and code readability.

# int ----> list
# returns factor list of a num
def factor(num):
    factors = []
    for i in range(num):
        if not (i == 0 or i == 1):
            if num % i == 0:
                factors.append(i)
    return factors

# int ----> bool
# returns true if num is prime
def prime(num):
    for i in range(num):
        if not(i == 0 or i == 1):
            if num % i == 0:
                return False
    return True

# main
# prints the factors of a number which are prime
def primeFactorization():
    num = int(input("Enter the number: "))
    factors = factor(num)
    prime_factors = []

    for item in factors:
        if prime(item):
            prime_factors.append(item)
    print(prime_factors)

primeFactorization()
\$\endgroup\$

1 Answer 1

3
\$\begingroup\$

For both of your functions prime and factor you have something like:

for i in range(num):
    if not (i == 0 or i == 1):
        if num % i == 0:
            factors.append(i)

when you could shorten by using range(start,stop):

for i in range(2,num):
    if num % i == 0:
        factors.append(i)
\$\endgroup\$
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.