Convert decimal to triple (base3) in python

I am trying to make a decimal number triple in a python function. My idea was to keep dividing until the ratio and balance are equal, but I can't get this to work. Here is 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
+6
source share
3 answers

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 divmodto 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'
+10
source

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)

b ( 2<=b<=10) .

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)
+6
import numpy as np

number=100 # decimal
ternary=np.base_repr(number,base=3)
print(ternary)
#10201
0
source

Source: https://habr.com/ru/post/1691648/


All Articles