[Verba] SPOILER: balanced ternary solution

Stuart D. Gathman stuart at gathman.org
Thu Jan 12 22:14:24 EST 2006


Here is a solution to printing balanced ternary:

print "Enter a number."
n = input()
b = n
s = []
while b > 0:
  c = "0+-"[b%3]
  print s,c,b
  if c == '-': b += 1
  s.append(c)
  b = b/3
s.reverse()
print "".join (s)

The 'if' command obeys the "b += 1" command if and only if
the condition "c == '-'" is True.  The "b += 1" is a shortcut
for "b = b + 1".

In class next time, we will create a unit test for balanced ternary
output.  This is an important programming technique to check that
your program is doing what you expect.  The first step toward that
end is to "encapsulate" our algorithm into a function:

def bal(b):
  "Convert a number to a balanced ternary string representation"
  s = []
  while b > 0:
    c = "0+-"[b%3]
    if c == '-': b += 1
    s.append(c)
    b = b/3
  s.reverse()
  return ''.join(s)

print "Enter a number."
n = input()
print bal(n)

-- 
	      Stuart D. Gathman <stuart at bmsi.com>
Business Management Systems Inc.  Phone: 703 591-0911 Fax: 703 591-6154
"Confutatis maledictis, flamis acribus addictis" - background song for
a Microsoft sponsored "Where do you want to go from here?" commercial.




More information about the Verba mailing list