Search code examples
pythonlistprime-factoring

How to apply a function to each element in a list, then make a list of the outputs?


Im trying to get prime factors by factorizing a number and adding the factors to list1, and then factorizing every number in list1 using the same method from before and adding to list2, so any prime factor will have a list length of 2 (If the number is a square number it prints out the square root twice, but since it is not a prime, it doesn't matter).

I don't know how to get it to apply my factors() function to every element in the list1 and make a list of all the factorized factors I've made.

import math
list1 = []
list2 = []
def factors(num1):

    for x in range(1, int(math.sqrt(num1) + 1)):
        if num1 % x == 0:
            list2.append(int(x))
            list2.append(int(num1/x))
            list2.sort()

print("enter a number:")
number = int(input())

for m in range(1, int(math.sqrt(number) + 1)):
    if number % m == 0:
        list1.append(int(m))
        list1.append(int(number/m))
        list1.sort()

for y in list1:
    factors(y)
print(list2)

desired output if 20 was the input

((1,1),(1,2),(1,2,2,4)(1,5),(1,2,5,10),(1,2,4,5,10,20))

Solution

  • In factors function, you are appending the factors themselves to list2 but as you want nested list of factors, you should create another list and append that to list2 instead. Changed code would look something like this.

    import math
    list1 = []
    list2 = []
    def factors(num1):
        factor_list = []
        for x in range(1, int(math.sqrt(num1) + 1)):
            if num1 % x == 0:
                factor_list.append(int(x))
                factor_list.append(int(num1/x))
        factor_list.sort()
        list2.append(factor_list)
    
    print("enter a number:")
    number = int(input())
    
    for m in range(1, int(math.sqrt(number) + 1)):
        if number % m == 0:
            list1.append(int(m))
            list1.append(int(number/m))
            list1.sort()
    
    for y in list1:
        factors(y)
    print(list2)
    

    Also, since you've already wrote the factors function, you can use it for factorizing the input number itself instead of writing the same code again. So a better version of the same code is:

    import math
    
    
    def factors(num1):
        factor_list = []
        for x in range(1, int(math.sqrt(num1) + 1)):
            if num1 % x == 0:
                factor_list.append(int(x))
                factor_list.append(int(num1/x))
        factor_list.sort()
        return factor_list
    
    print("enter a number:")
    number = int(input())
    
    list1 = factors(number)
    list2 = [factors(x) for x in list1]
    
    print(list2)
    

    Following up on the comment, if you want to include only on those elements which have length 2, you can use another list comprehension for that:

    list2 = [x for x in list2 if len(x)==2]