[Python] Prime factorization using list comprehension in Python

Discussão em 'Python' iniciado por Stack, Janeiro 21, 2025.

  1. Stack

    Stack Membro Participativo

    How to write a function which returns a list of tuples like (ci, ki) for n such that n = c1k1 c2k2 ... ciki is a prime number?

    For example: 12600 = 23 · 32 · 52 · 71

    Desired output: [(2, 3), (3, 2), (5, 2), (7, 1)]

    I know how to do it with while but is it possible to do it using list comprehension? Efficiency is not required in this task.

    # naive function
    def is_prime(n):
    return n > 1 and all(n % i != 0 for i in range(2, n))

    # while version
    def factorization_while(n):
    res = []
    for i in range(1, n + 1):
    if is_prime(i):
    j = 0
    while n % i == 0:
    n = n // i
    j += 1
    if j != 0:
    res.append((i, j))
    return res

    # list comprehension version
    def factorization(n):
    return [
    (i, j) for i in range(1, n + 1) if is_prime(i) \
    and n % i == 0 ... # add smth
    ]

    Continue reading...

Compartilhe esta Página