Search code examples
pythonyieldpi

How would this be written without using yield?


I've tried and failed multiple times trying to replace yield, but I don't seem to be successful, the goal is to have the same function, without yield.

def calcPi(limit):  # Generator function
    """
    Prints out the digits of PI
    until it reaches the given limit
    """

    q = 1
    r = 0
    t = 1
    k = 1
    n = 3
    l = 3

    decimal = limit
    counter = 0

    while counter != decimal + 1:
        if 4 * q + r - t < n * t:
            # yield digit
            yield n
            # insert period after first digit
            if counter == 0:
                yield '.'
            # end
            if decimal == counter:
                print('')
                break
            counter += 1
            nr = 10 * (r - n * t)
            n = ((10 * (3 * q + r)) // t) - 10 * n
            q *= 10
            r = nr
        else:
            nr = (2 * q + r) * l
            nn = (q * (7 * k) + 2 + (r * l)) // (t * l)
            q *= k
            t *= l
            l += 2
            k += 1
            n = nn
            r = nr

Added the full function as people were asking for it in the comments,


Solution

  • Just define a list and collect the digits:

    def calcPi(limit):  # Generator function
        """
        Collects the digits of PI
        until it reaches the given limit
        """
        pi = []
        ...
    
        while ...:
            ...
            # yield n
            pi.append(n)
            ...
                #break
                return pi