Home > Enterprise >  Making a list of tuples from prime factorization output for any value?
Making a list of tuples from prime factorization output for any value?

Time:10-23

How do I turn the resulting tuple into a list of tuples containing the prime numbers and how many times it appers. I've tried tuples = tuple(2, factors.count(2)) and then doing the same for other numbers and then do list(zip(list1,list2) but that would just hard code the output: E,g

In: 288

Out: [(2, 5), (3, 2)]

def prime_factors(n):
    i = 2
    factors = []

    while i * i <= n:
        if n % i:
            i  = 1
        else:
            n //= i
            factors.append(i)
    if n > 1:
        factors.append(n)

    tuple1 = tuple(factors)
    return tuple1

    

n = int(input())
print(prime_factors(n))

CodePudding user response:

You need collections.Counter.

import collections
list(collections.Counter((2,2,2,3,4)).items())

gives

[(2, 3), (3, 1), (4, 1)]
  • Related