Está en la página 1de 12

Laboratorio de Algoritmos y Estructuras de Datos

Página 2 de 2

Alumno(s) Nota

Diego Brayan Laura Machaca

Diego Freddy Mango Rosas

Elvis Quecara Cruz

Mamani Coila Diego Valerio

Oviedo Turpo Eusebio Frank

Jorge Manuel Firata Quispe


Grupo
Ciclo I
Fecha de entrega
Laboratorio de Algoritmos y Estructuras de Datos
Página 1 de 10

I.- OBJETIVOS:
• Definir las reglas de ejecución de árboles de expresión
• Ejecutar operaciones matemáticas basicas en árboles de expresión.

II.- SEGURIDAD:
Advertencia:
En este laboratorio está prohibida la manipulación del
hardware, conexiones eléctricas o de red; así como la
ingestión de alimentos o bebidas.

III.- FUNDAMENTO TEÓRICO:


• Revisar el texto guía que está en el campus Virtual.

IV.- NORMAS EMPLEADAS:


• No aplica

V.- RECURSOS:
• En este laboratorio cada alumno trabajará con un equipo con Windows 10.

VI.- METODOLOGÍA PARA EL DESARROLLO DE LA TAREA:


• El desarrollo del laboratorio es individual.

VII.- PROCEDIMIENTO:

EJERCICIO DE APLICACIÓN

BinaryTreeNode.py
'''
Created on Mar 11, 2019
@author: jgomezm
@version: 1.2 April 29,2020
'''
class BinaryTreeNode:

def __init__(self, data, left = None, right = None):


self.data = data # value node
self.left = left # left child
self.right = right # right child

1.- Encontrar el valor máximo y mínimo de un árbol

from BinaryTreeNode import BinaryTreeNode

def findMaxRecursive(tree):

# Base case
if tree is None:
return float('-inf') # Mininum value
Laboratorio de Algoritmos y Estructuras de Datos
Página 2 de 10

data = tree.data
left_max = findMaxRecursive(tree.left)
right_max = findMaxRecursive(tree.right)

return max([data, left_max, right_max])

'''
Binary Tree

1
|
----------------------
| |
2 3

'''

childrenLeft = BinaryTreeNode(2)
childrenRight = BinaryTreeNode(3)
root = BinaryTreeNode(1,childrenLeft,childrenRight)

max_data = findMaxRecursive(root)
print(max_data)

En el siguiente ejercicio, construir el árbol y encontrar el máximo y mínimo valor

MINIMO
Laboratorio de Algoritmos y Estructuras de Datos
Página 3 de 10

MAXIMO

2.- Encontrar un valor en un árbol

from BinaryTreeNode import BinaryTreeNode

#
def findDataRecursive(root, dataSearch, nro_times=0):

if root == None:
Laboratorio de Algoritmos y Estructuras de Datos
Página 4 de 10

return nro_times

tmp_nro_times = nro_times

if root.data == dataSearch:
tmp_nro_times +=1

return tmp_nro_times + \
findDataRecursive(root.left, dataSearch, nro_times) + \
findDataRecursive(root.right, dataSearch, nro_times)

#
#
# Resolution
# 1
# 2 3
# 7 5 6 7

root = BinaryTreeNode(1)
root.left = BinaryTreeNode(2)
root.right = BinaryTreeNode(3)
root.left.left = BinaryTreeNode(4)
root.left.right = BinaryTreeNode(5)
root.right.left = BinaryTreeNode(6)
root.right.right = BinaryTreeNode(7)

dataSearch = 7
nro_times = findDataRecursive(root, dataSearch)
print("Se encontro el valor de %d, %d veces" % (dataSearch, nro_times))

Created on Mar 11, 2019


@author: jgomezm
@version: 1.2 April 29,2020
'''
class BinaryTreeNode:

def __init__(self, data, left = None, right = None):


self.data = data # value node
self.left = left # left child
self.right = right # right child

1.- Encontrar el valor máximo y mínimo de un árbol

from BinaryTreeNode import BinaryTreeNode

def findMaxRecursive(tree):

# Base case
if tree is None:
Laboratorio de Algoritmos y Estructuras de Datos
Página 5 de 10

return float('-inf') # Mininum value

data = tree.data
left_max = findMaxRecursive(tree.left)
right_max = findMaxRecursive(tree.right)

return max([data, left_max, right_max])

'''
Binary Tree

1
|
----------------------
| |
2 3

'''

childrenLeft = BinaryTreeNode(2)
childrenRight = BinaryTreeNode(3)
root = BinaryTreeNode(1,childrenLeft,childrenRight)

max_data = findMaxRecursive(root)
print(max_data)

¿ Se puede saber cuantas veces el número se repite, si hay varios número iguales?, es
posible?
Si es posible poder saber las veces que número se repite porque la función tiene un contador.

3.- Encontrar suma de datos de un árbol

def sumRecursive(root):
if (root == None):
return 0
return root.data + \
sumRecursive(root.left) + \
sumRecursive(root.right)

#
# Resolution
# 1
# 2 3
# 7 5 6 7

root = BinaryTreeNode(1)
root.left = BinaryTreeNode(2)
root.right = BinaryTreeNode(3)
root.left.left = BinaryTreeNode(7)
root.left.right = BinaryTreeNode(5)
root.right.left = BinaryTreeNode(6)
Laboratorio de Algoritmos y Estructuras de Datos
Página 6 de 10

root.right.right = BinaryTreeNode(7)

tmp = sumRecursive(root)
print("La suma del arbol es %d" % (tmp))

- Obtener el producto de todos los nodos del árbol

- Obtener el producto de todos los número pares del nodos del árbol

4.- Árboles genéricos

########################################
# Generic Tree
########################################
Laboratorio de Algoritmos y Estructuras de Datos
Página 7 de 10

class TreeNode:

#Constructor
def __init__(self, data=None):
self.data = data
self.firstChild = None
self.nextSibling = None

def findSum(root):
if(root == None):
return 0
return root.data + \
findSum(root.firstChild) + \
findSum(root.nextSibling)

# programa principal
#
# A,1
# / \ \ \
# | | | |
# B,2 C,3 D,4 E,10
# | |
# | |
# G,20 H,15
#
if __name__ == '__main__':

nodeA = TreeNode(1)
nodeB = TreeNode(2)
nodeC = TreeNode(3)
nodeD = TreeNode(4)
nodeE = TreeNode(10)
nodeG = TreeNode(20)
nodeH = TreeNode(15)

nodeA.firstChild = nodeB
nodeB.nextSibling = nodeC
nodeC.nextSibling = nodeD
nodeC.firstChild = nodeG
nodeD.nextSibling = nodeE # Defino su hermano
nodeD.firstChild = nodeH # Defino un hijo

# Suma
print(findSum(nodeA))

'''

Ejercicio : Calcular la suma del siguiente


arbol generico

17
/ | \
Laboratorio de Algoritmos y Estructuras de Datos
Página 8 de 10

/ | \
3 4 5
/|\ |
3 4 5 10

'''

5.- Expresiones genéricas – ejecución simple

#
class Node:
def __init__(self, value):
self.value = value
self.left = None
self.right = None

def eval(self):

if self.right is not None and self.left is not None :


if self.value == '+':
return self.left.eval() + self.right.eval()
elif self.value == '*':
return self.left.eval() * self.right.eval()
else:
return float(self.value)
Laboratorio de Algoritmos y Estructuras de Datos
Página 9 de 10

#################################
# First Case : (5+3)*6
#
# *
# + 6
# 5 3
#################################
def evalManual():

opeNodeA = Node(5)
opeNodeB = Node(3)

sumNode = Node('+')
sumNode.left = opeNodeA
sumNode.right = opeNodeB

opeNodeC = Node(6)
mulNode = Node('*')
mulNode.left = sumNode
mulNode.right = opeNodeC

print(mulNode.eval())

Ejecutar la función evalManual()


#################################
# Main
#################################
if __name__ == '__main__':
'''
Este metodo es para
'''
evalManual()
# evalPostfixExpression()
# convertIndorToPostfixExp()
# evalIndorExpression()

Ejercicio , resolver ((2 + 4) * 2 + 5)


Laboratorio de Algoritmos y Estructuras de Datos
Página 10 de 10

CONCLUSIONES:
1. El código representado en árboles de expresión se puede compilar y
ejecutar.
2. Existe un orden de prioridad para los operadores, que de menor a mayor es
el siguiente: suma (+) y resta (-), multiplicación (*) y división (/),
exponenciación (^)
3. En un árbol de expresión todos los operadores tienen dos operandos.

También podría gustarte