Python Ternary Rescursion
<p>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.</p>

<pre><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&lt;3:
        return str(n)
    return numToTernary(n//3)+
</code></pre>

<p>So the big idea with all base change is the following:</p>

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

<p>Now the for the reverse operation: you have a <code>number n</code> in <code>base 10</code> and want to turn it in <code>base b</code>. 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 <code>base b</code> of n. I know that <code>d2*bÂ² + d1*b + d0 = n</code>. That means that  <code>(d2*b + d1)*b + d0 = n</code> so we recognize the result of an euclidian division where d0 is the remainder of the euclidian division of n by d : <code>d0=n%d</code>. We have identified d0 as the remainder so the expression in parentheses is the <code>quotien q</code>, <code>q=n//b</code> so we have a new equation to solve using the exact same method (hence the recursion) <code>d2*b + d1 = q</code>.</p>

<p>And all that translate to the code you almost had :</p>

<pre><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&lt;3:
        return str(n)
    return numToTernary(n//3)+str(n%3)

print(numToTernary(10))
Out[1]: '101'
</code></pre>

python recursion ternary