Convert decimal to ternary(base3) in python

Question:

I am trying to make a decimal number ternary in a python function. My idea was to keep dividing until the quotient and remainder were equal, but I can’t seem to get that to work. Here’s my code:

l = 1


#problem code
def ternary(n):
    e = n/3
    q = n%3
    e= n/3
    q= e%3
    print q

r = input("What number should I convert?: ")
k = bin(r)
v = hex(r)
i = oct(r)
print k+"(Binary)"
print v+"(Hex)"
print i+"(Octals)"
ternary(r)
l+=1
# Variables:
#l,r,k,v,i 
#n,q,e
Asked By: Sidsy

||

Answers:

My idea was to keep dividing until the quotient and remainder were equal, but I can’t seem to get that to work.

Yeah, something like that. Essentially, you want to keep dividing by 3, and collect the remainders. The remainders then make up the final number. In Python, you can use divmod to divide and collect the remainder.

def ternary (n):
    if n == 0:
        return '0'
    nums = []
    while n:
        n, r = divmod(n, 3)
        nums.append(str(r))
    return ''.join(reversed(nums))

Examples:

>>> ternary(0)
'0'
>>> ternary(1)
'1'
>>> ternary(2)
'2'
>>> ternary(3)
'10'
>>> ternary(12)
'110'
>>> ternary(22)
'211'
Answered By: poke

This can also be done with recursion.

def ternary(n):
    e = n//3
    q = n%3
    if n == 0:
        return '0'
    elif e == 0:
        return str(q)
    else:
        return ternary(e) + str(q)

More generally, you can convert to any base b (where 2<=b<=10) with the following recursive function.

def baseb(n, b):
    e = n//b
    q = n%b
    if n == 0:
        return '0'
    elif e == 0:
        return str(q)
    else:
        return baseb(e, b) + str(q)
Answered By: Chris Mueller

You can also use the implementation of NumPy:
https://numpy.org/doc/stable/reference/generated/numpy.base_repr.html?highlight=base_repr#numpy.base_repr

Though, I agree that a function for ternary exclusively is faster.

import numpy as np

number=100 # decimal
ternary=np.base_repr(number,base=3)
print(ternary)
#10201
Answered By: SzorgosDiák

Here is a closed form solution. It returns a little-endian array of integers, and it works for any natural numbered value and base.

def base(b,n):
    return list(reversed([n%b**(i+1)//b**i
                          for i in range(max(1,math.floor(math.log(max(1,n),b))+1))]))

Example:

>>>base(3,7)
[2,1]
Answered By: 16807
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.