Conversion of ternary into balanced ternary as start iterating from Least Significant Bit ( i . e 0 th ) , if encountered 0 or 1 , safely skip and pass carry 0 further 2 , replace it to - 1 and pass carry 1 further 3 , replace it to 0 and pass carry 1 further
def balTernary ( ter ) : NEW_LINE INDENT carry , base , i = 0 , 10 , 31 NEW_LINE while ter > 0 : NEW_LINE INDENT rem = ( ter % base ) + carry NEW_LINE if rem == 0 : NEW_LINE INDENT arr [ i ] = 0 NEW_LINE carry , i = 0 , i - 1 NEW_LINE DEDENT elif rem == 1 : NEW_LINE INDENT arr [ i ] = 1 NEW_LINE carry , i = 0 , i - 1 NEW_LINE DEDENT elif rem == 2 : NEW_LINE INDENT arr [ i ] = - 1 NEW_LINE carry , i = 1 , i - 1 NEW_LINE DEDENT elif rem == 3 : NEW_LINE INDENT arr [ i ] = 0 NEW_LINE carry , i = 1 , i - 1 NEW_LINE DEDENT ter = ter // base NEW_LINE DEDENT if carry == 1 : NEW_LINE INDENT arr [ i ] = 1 NEW_LINE DEDENT DEDENT