I've been trying to convert balanced ternary numbers through the negate function in python
def convert_to_balanced_ternary(n):
if n == 0:
return '0'
negative = n < 0
bt = ''
while n > 0:
r = n % 3
if r == 0:
bt = '0' + bt
n = n // 3
elif r == 1:
if negative:
bt = '-' + bt
else:
bt = '+' + bt
n = n // 3
else:
if negative:
bt = '+' + bt
else:
bt = '-' + bt
n = (n + 1) // 3
return bt
def negate(n):
temp = n.replace('-', '+') or n.replace('+', '-') or n.replace('0', '0')
return temp
And I can get the '-' to convert to '+' but '+' won't convert to '-'. '0' seems to pass through just fine.
negate('+-0')
'++0'