Here is base conversion function written to deal also with negative bases.
Not yet balanced ternary, where numbers themselves can be negative, maybe later I add it.. Based on the code in the wikipedia article, which has bug for converting 0.[Edit: I fixed the bug in wikipedia]

138 Views
``````""" Program to show number in different bases including the negative bases
val function for calculating the value of string as number (like extended int) added
"""

""" produce digits of number at base base, also for negative base,
in reverse order """
if n < 0 and base > 0:
negative = '-'
n = -n
else:
negative = ''

# case zero
if not n:
yield '0'
else:
while n != 0:
n, remainder = divmod(n, base)
if remainder < 0:
n, remainder = n + 1, remainder - base
yield str(remainder) if remainder < 10 else chr(ord('A')+remainder-10)
if negative: yield negative

def negabase(n, base=-3):

def val(number_string, base=-3):
return sum(int(n) * base ** p for p, n in enumerate(reversed(number_string)))

print('%10s %10s %10s %10s %10s %10s' % ('dec', 'hex', 'bin', 'negabin', 'ternary', 'negaternary'))
for t in range(-32,+33):
print('%10s %10s %10s %10s %10s %10s' % (t, negabase(t, 16), negabase(t, 2), negabase(t, -2), negabase(t, 3), negabase(t, -3)))
assert val(negabase(t)) == t``````

IT Pro doing Eng-Fin-Eng translations

Few first functions to show the values and negate before tackling the generating part for balanced ternary

``````def balanced_ternary(number_string):
return val([-1 if c == '-' else (1 if c == '+' else 0)
for c in number_string], 3)

def neg(balanced):
return balanced.replace('-', '*').replace('+', '-').replace('*', '+')

if __name__  == '__main__':
b = '-0+'
print('\nBalanced ternary %r value is %i' % (b, balanced_ternary(b)))
assert balanced_ternary(b) == -balanced_ternary(neg(b))
``````