Not logged in. Login

Exercise 12

With Commas

In recursion2.py, write a recursive function with_commas that takes a positive integer and returns a string containing its representation with commas every three places. That is, you should return a string with a comma separating the thousands, millions, …. You can assume the argument is a positive integer.

>>> with_commas(1234567)
'1,234,567'
>>> with_commas(4)
'4'
>>> with_commas(123)
'123'
>>> with_commas(91273490123741290347)
'91,273,490,123,741,290,347'

Recursive Prime Factors

In recursion2.py, write a recursive function prime_factorization that returns a list of prime numbers that represent the prime factorization of the argument. (i.e. all numbers in the list should be prime, and the product of them should be the argument.) You can assume the argument is an integer 2 or larger.

>>> prime_factorization(120)
[2, 2, 2, 3, 5]
>>> prime_factorization(256498)
[2, 11, 89, 131]
>>> prime_factorization(13)
[13]

You can use this function, which returns the smallest factor of a number (which will be a prime number).

def first_factor(n):
    """
    Returns the smallest factor of n.
    """
    if n < 2:
        raise ValueError("Argument must be >= 2")
    f = 2
    while n % f != 0:
        f = f + 1
    return f

Submitting

Submit all of your work through CourSys.

Updated Thu July 18 2024, 17:21 by ggbaker.