Sharedsage_worksheets / ternary_number_system.sagewsOpen in CoCalc
Author: Ken Levasseur
Description: Worksheets related to Applied Discrete Structures
def b_div_by_3(n): if n%3==2: return (n//3)+1 else: return n//3
def b_mod_3(n): if n%3==2: return -1 else: return n%3
def tern(n): if n==0: return [0] elif abs(n)==1: return [n] else: return [b_mod_3(n)]+tern(b_div_by_3(n))
def tern_powers(n): t=tern(n) l=len(t) return [[3^(k) for k in range(len(t))],t]
tern_powers(17)
[[1, 3, 9, 27], [-1, 0, -1, 1]]
from sage.plot.polygon import Polygon
def visual_tern(n): dat=tern_powers(n) exp=1/2 w=2*abs(n)^exp pic=Graphics() nb=0 pb=0 nbase=[] pbase=[] for k in reversed(range(len(dat[0]))): if dat[1][k]>0: pbase=pbase+[dat[0][k]] s=dat[0][k]^exp.n() pic+=polygon([(w-s,pb),(w+s,pb),(w+s,pb+s),(w-s,pb+s)]) pic+=text(str(dat[0][k]),(w,pb+s/2),color='yellow') pb+=s elif dat[1][k]<0: nbase=nbase+[dat[0][k]] s=dat[0][k]^exp.n() pic+=polygon([(-w+s,nb),(-w-s,nb),(-w-s,nb+s),(-w+s,nb+s)]) pic+=text(str(dat[0][k]),(-w,nb+s/2),color='yellow') nb+=s if n>0: s=n^exp pic+=polygon([(-w+s,nb),(-w-s,nb),(-w-s,nb+s),(-w+s,nb+s)],color='black') pic+=text(str(n),(-w,nb+s/2),color='red') else: s=(-n)^exp pic+=polygon([(w+s,pb),(w-s,pb),(w-s,pb+s),(w+s,pb+s)],color='black') pic+=text(str(n),(w,pb+s/2),color='red') pic+=line([(-2*w,0),(2*w,0)],color='black') pic+=polygon([(0,0),(w/4,-w/4),(-w/4,-w/4)],color='red') pic+=text(str(n)+" = sum("+str(pbase)+")-sum("+str(nbase)+")",(0,-(abs(n)^exp))) pic.show(axes=False)
visual_tern(178)
visual_tern(7)
@interact def _(n=(1..2000)): visual_tern(n)
Interact: please open in CoCalc
for k in reversed(range(5)): print k
4 3 2 1 0
L=range(5)
Error in lines 2-3 Traceback (most recent call last): File "/cocalc/lib/python2.7/site-packages/smc_sagews/sage_server.py", line 1044, in execute exec compile(block+'\n', '', 'single', flags=compile_flags) in namespace, locals File "", line 1, in <module> TypeError: 'NoneType' object is not iterable