base3equilibree.py

Created by nicolas-patrois

Created on December 15, 2018

382 Bytes

Décompose un nombre en base 3 où les chiffres sont 1, 0 et −1 (noté T). Comme 100=3^4+3^3-3^2+3^0, on note 100=11T01 en base 3 équilibrée.


def base3eq(n):
  if n==0:
    return "0"
  if n<0:
    n*=-1
    rev=-1
  elif n>0:
    rev=1
  ch=""
  i=1
  while n:
    r=n%(i*3)//i
    if r==2:
      r=-1
    ch={1:"+",0:"0",-1:"-"}[r]+ch
    n-=r*i
    i*=3
  ch="+"+ch[1:]
  if rev==1:
    ch=ch.replace("+","1").replace("-","T")
  elif rev==-1:
    ch=ch.replace("+","T").replace("-","1")
  return ch