Documentos de Académico
Documentos de Profesional
Documentos de Cultura
Laboratorio 6.2:
I
OBJETIVOS
II
TEMAS A TRATAR
III
MARCO TEORICO
1. Código Huffman
El codificador Huffman crea una estructura arbórea ordenada con todos los
símbolos y la frecuencia con que aparecen. Las ramas se construyen en forma
recursiva comenzando con los símbolos menos frecuentes.
La construcción del árbol se realiza ordenando en primer lugar los símbolos según
la frecuencia de aparición. Los dos símbolos con menor frecuencia de aparición
se eliminan sucesivamente de la lista y se conectan a un nodo cuyo peso es igual
El algoritmo es el siguiente:
! Entrada: Gráfica conexa G con vértices ordenados v1,v2,…vn
! Salida: Árbol de expansión T.
bla(V, E) {
//V = vértices ordenados v1, . . . , vn; E = aristas
de la forma (f, x). Una vez más, no es posible agregar una arista de la forma
(f, x), así́ que regresamos a e, el padre de f. Esta vez se puede agregar la
arista (e, g). En este punto, no hay más aristas que agregar, de manera
que regresamos a la raíz y el procedimiento termina.
El algoritmo es el siguiente:
De la siguiente manera:
myTree = ['a', ['b', ['d', [], []], ['e', [], []] ], ['c', ['f',
[], []],[] ]]
def izqArbin(a):
return a[1]
def derArbin(a):
return a[2]
def vacioArbin(a):
return a == []
def preOrden(arbin):
if not vacioArbin(arbin):
print raizArbin(arbin)
preOrden(izqArbin(arbin))
preOrden(derArbin(arbin))
def inOrden(arbin):
if not vacioArbin(arbin):
inOrden(izqArbin(arbin))
print raizArbin(arbin)
inOrden(derArbin(arbin))
def postOrden(arbin):
if not vacioArbin(arbin):
postOrden(izqArbin(arbin))
postOrden(derArbin(arbin))
print raizArbin(arbin)
Probamos el programa con el árbol anterior para que nos muestre sus
recorridos:
>>> preOrden(myTree)
a
b
d
e
c
f
>>> inOrden(myTree)
d
b
e
a
f
c
>>> postOrden(myTree)
d
e
b
f
c
a
def insArbinOr(arbinOr,elem):
if arbinOr==[]:
return [elem,[],[]]
else:
if elem > arbinOr[0]:
arbinOr[2] = insArbinOr(arbinOr[2],elem)
else:
arbinOr[1] = insArbinOr(arbinOr[1],elem)
return arbinOr
def mayorElem(arbinOr):
if arbinOr[2]==[] :
return arbinOr[0]
else:
return mayorElem(arbinOr[2])
>>> a2 = inicArbinOr()
>>> a2
[]
>>> a2 = insArbinOr(a2, 6)
>>> a2
[6, [], []]
>>> a2 = insArbinOr(a2, 8)
>>> a2
[6, [], [8, [], []]]
>>> a2 = insArbinOr(a2, 3)
>>> a2
[6, [3, [], []], [8, [], []]]
>>> a2 = insArbinOr(a2, 7)
>>> a2
[6, [3, [], []], [8, [7, [], []], []]]
>>> a2 = insArbinOr(a2, 1)
>>> a2
[6, [3, [1, [], []], []], [8, [7, [], []], []]]
>>> a2 = elimArbinOr(a2, 7)
>>> a2
[6, [3, [1, [], []], []], [8, [], []]]
>>> a2 = elimArbinOr(a2, 6)
>>> a2
[3, [1, [], []], [8, [], []]]
>>> a2 = insArbinOr(a2, 2)
>>> a2
[3, [1, [], [2, [], []]], [8, [], []]]
>>> a2 = elimArbinOr(a2, 3)
>>> a2
[2, [1, [], []], [8, [], []]]
>>> estaArbinOr(a2, 1)
True
>>> estaArbinOr(a2, 11)
False
>>> a2
[2, [1, [], []], [8, [], []]]
>>> a2 = insArbinOr(a2, 6)
>>> a2 = insArbinOr(a2, 7)
>>> a2 = insArbinOr(a2, 17)
>>> a2
[2, [1, [], []], [8, [6, [], [7, [], []]], [17, [],
[]]]]
>>> a2 = elimArbinOr(a2, 8)
>>> a2
[2, [1, [], []], [7, [6, [], []], [17, [], []]]]
def alturaArbin(a):
if vacioArbin(a):
return 0
elif vacioArbin(izqArbin(a)) and vacioArbin(derArbin(a)):
return 1
else:
izq = alturaArbin(izqArbin(a))
der = alturaArbin(derArbin(a))
if izq<der:
return der + 1
else:
return izq + 1
Aquí tenemos que comparar los datos y la estructura del árbol. Por tanto
empezamos por comparar arboles vacíos y luego sus subárboles. Así:
Árboles isomorfos
Árboles semejantes
IV
(La práctica tiene una duración de 4 horas) ACTIVIDADES
def encode(symb2freq):
"""Huffman encode the given dict mapping symbols to weights"""
heap = [[wt, [sym, ""]] for sym, wt in symb2freq.items()]
heapify(heap)
while len(heap) > 1:
lo = heappop(heap)
hi = heappop(heap)
for pair in lo[1:]:
pair[1] = '0' + pair[1]
for pair in hi[1:]:
pair[1] = '1' + pair[1]
heappush(heap, [lo[0] + hi[0]] + lo[1:] + hi[1:])
return sorted(heappop(heap)[1:], key=lambda p: (len(p[-1]), p))
G2 = {
'a': list('bd'),
'b': list('ace'),
'c': list('bf'),
'd': list('aeh'),
'e': list('bdfi'),
'f': list('cegj'),
'g': list('fjl'),
'h': list('dik'),
'i': list('ehjk'),
'j': list('fgi'),
'k': list('him'),
'l': list('g'),
'm': list('k'),
}
print('-'*70)
print("breadth_first de G2 = \\")
pprint(G2)
T2 = breadth_first(G2, 'e')
print("es T2 = \\")
pprint(T2)
#
print('-'*70)
breadth_first de G2 = \
{'a': ['b', 'd'],
'b': ['a', 'c', 'e'],
'c': ['b', 'f'],
'd': ['a', 'e', 'h'],
'e': ['b', 'd', 'f', 'i'],
'f': ['c', 'e', 'g', 'j'],
'g': ['f', 'j', 'l'],
'h': ['d', 'i', 'k'],
'i': ['e', 'h', 'j', 'k'],
'j': ['f', 'g', 'i'],
'k': ['h', 'i', 'm'],
'l': ['g'],
'm': ['k']}
es T2 = \
{'a': ['b'],
'b': ['e', 'a', 'c'],
'c': ['b'],
'd': ['e', 'h'],
'e': ['b', 'd', 'f', 'i'],
'f': ['e', 'g', 'j'],
'g': ['f', 'l'],
'h': ['d'],
'i': ['e', 'k'],
'j': ['f'],
'k': ['i', 'm'],
'l': ['g'],
'm': ['k']}
----------------------------------------------------------------------
C:\Python27>
T = {r: []}
visit(G, r, T)
return T
G2 = {
'a': list('bd'),
'b': list('ace'),
'c': list('bf'),
'd': list('aeh'),
'e': list('bdfi'),
'f': list('cegj'),
'g': list('fjl'),
'h': list('dik'),
'i': list('ehjk'),
'j': list('fgi'),
'k': list('him'),
'l': list('g'),
'm': list('k'),
}
T2 = depth_first(G2, 'e')
print("depth_first de G2 es T2 = \\")
print(T2)
#
print(‘-'*70)
depth_first de G2 es T2 = \
{'a': ['b', 'd'],
'b': ['e', 'a'],
'c': ['f'],
'd': ['a', 'h'],
'e': ['b'],
'f': ['j', 'c', 'g'],
'g': ['f', 'l'],
'h': ['d', 'i'],
'i': ['h', 'j', 'k'],
'j': ['i', 'f'],
'k': ['i', 'm'],
'l': ['g'],
'm': ['k']}
----------------------------------------------------------------------
C:\Python27>
def printQueens(q):
N = len(q)
for i in range(N):
for j in range(N):
if q[i] == j:
print "Q",
else:
print "*",
print " "
print " "
def CuatroReinas(q,n):
N = len(q)
if n==N:
printQueens(q)
Fin = True
else:
for i in range(N):
q[n] = i
if (isConsistent(q,n)):
CuatroReinas(q,n+1)
print('-'*70)
n = 4
CuatroReinas([0 for x in range(n)],0)
print('-'*70)
C:\Python27>python "c:\Users\Carlo\Documents\Python\CuatroReinas.py"
----------------------------------------------------------------------
* Q * *
* * * Q
Q * * *
* * Q *
* * Q *
Q * * *
* * * Q
* Q * *
----------------------------------------------------------------------
C:\Python27>
V
EJERCICIOS
a.
b.
c.
Inorden: h
a m
f–b–g– –c n– –d
VI
CUESTIONARIO
VII
BIBLIOGRAFIA Y REFERENCIAS
! LEE KENT D. Python programming fundamentals. New York. Springer Verlag. 2011.
! GORVATOV V.A. Fundamentos de la Matemática Discreta. Rusia. Edit. Mir Moscu. 1988.
! Documentación Python 2.7.9 Tutorial de Python. www.python.org