Search code examples
pythonrecursionternary

Python Ternary Rescursion


I'm creating two functions one, that returns the ternary representation for a base 10 number, and one that returns the base 10 representation for a ternary number using recursion. For example 52 would return 1221. Right now, I have this down, but I'm not sure how to make it. I'm mostly confused with the aspect of the 2 in ternary representation and how to implement that into code.

def numToTernary(n):
 '''Precondition: integer argument is non-negative.
    Returns the string with the ternary representation of non-negative integer
    n. If n is 0, the empty string is returned.'''
    if n==0:
        return ''
    if n<3:
        return str(n)
    return numToTernary(n//3)+

Solution

  • So the big idea with all base change is the following:

    You take a number n written in base b as this 123. That means n in base 10 is equal to 1*b² + 2*b + 3 . So convertion from base b to base 10 is straigtforward: you take all digits and multiply them by the base at the right power.

    Now the for the reverse operation: you have a number n in base 10 and want to turn it in base b. The operation is simply a matter of calculating each digit in the new base. (I'll assume my result has only three digits for the following example) So I am looking for d2,d1,d0 the digits in base b of n. I know that d2*b² + d1*b + d0 = n. That means that (d2*b + d1)*b + d0 = n so we recognize the result of an euclidian division where d0 is the remainder of the euclidian division of n by d : d0=n%d. We have identified d0 as the remainder so the expression in parentheses is the quotien q, q=n//b so we have a new equation to solve using the exact same method (hence the recursion) d2*b + d1 = q.

    And all that translate to the code you almost had :

    def numToTernary(n):
        '''Precondition: integer argument is non-negative.
        Returns the string with the ternary representation of non-negative integer
        n. If n is 0, the empty string is returned.'''
        if n==0:
            return ''
        if n<3:
            return str(n)
        return numToTernary(n//3)+str(n%3)
    
    print(numToTernary(10))
    Out[1]: '101'