""" 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

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

    # case zero    
    if not n:
        yield '0'
        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):
    return ''.join(reversed(list(reversed_negadigits(n, base))))

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/Science/Contracts/Religious translation/interpreting FIN-ENG-FIN
Python programming

4 Years
Discussion Span
Last Post by pyTony

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))

Edited by pyTony: link to document

Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.