My idea was to keep dividing until the ratio and balance are equal, but I can't get this to work.
Yes, something like that. Essentially, you want to keep dividing by 3 and collecting leftovers. Then the remainders make up the final number. In Python, you can use divmod
to separate 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'
source
share