In [ ]:
def listTree(n):
if n == 0:
return [None]
else:
res = []
for i in range(n):
for g in listTree(i):
for d in listTree(n-1-i):
res.append((g,d))
return res
In [2]:
for t in listTree(3): print t
In [ ]:
In [3]:
@cached_function
def catalan(n):
print "Calcul de catalan(%i)"%n
if n == 0:
return 1
else:
return sum(catalan(i)*catalan(n-1-i) for i in range(n))
In [4]:
catalan(10)
Out[4]:
In [5]:
[catalan(i) for i in range(10)]
Out[5]:
In [ ]:
In [6]:
def unrankTree(n, i):
if i >= catalan(n):
raise ValueError, (n, i)
elif n == 0:
return None
else:
ng = 0
while i >= catalan(ng) * catalan(n-1-ng):
i -= catalan(ng) * catalan(n-1-ng)
ng += 1
ig = i // catalan(n-1-ng)
id = i % catalan(n-1-ng)
return (unrankTree(ng, ig), unrankTree(n-1-ng, id))
In [7]:
N = 10
l = [unrankTree(N, i) for i in range(catalan(N))]
l == listTree(N)
Out[7]:
In [8]:
N = 100
In [9]:
c = catalan(100)
In [10]:
h = randint(0, c); h
Out[10]:
In [11]:
unrankTree(N, h)
Out[11]:
In [12]:
def prof(tr):
if tr is None: return 0
else:
return 1+max(prof(tr[0]), prof(tr[1]))
In [13]:
prof(unrankTree(N, h))
Out[13]:
In [ ]: