Está en la página 1de 53

TRABAJOS DE TEORIA DE PROGRAMACION

Presentado por:

Cristian Javier Bravo Valenzuela


Código: 101718011404

Camilo Sánchez García


Código: 101718010671

Presentado a:
Mauricio Maca Chagüendo

Programa: Matemáticas

FACULTAD DE CIENCIAS NATURALES EXACTAS Y DE LA


EDUCACION
Contents
Procedimiento con lineas .................................................................................................................... 3
Líneas oblicuas ................................................................................................................................ 3
Seguimiento ................................................................................................................................ 4
lienas oblicuas 2 .............................................................................................................................. 4
Seguimiento2 .............................................................................................................................. 5
Lienas oblicuas 3 ............................................................................................................................. 5
Seguimiento3 .............................................................................................................................. 6
Lineas oblicuas 4 ............................................................................................................................. 7
Seguimiento4 .............................................................................................................................. 7
Procedimiento estrella ........................................................................................................................ 8
Estrella ............................................................................................................................................. 8
Pseudocódigo triángulos y rombo ...................................................................................................... 9
Triangulo1 ................................................................................................................................... 9
Triangulo2 ................................................................................................................................... 9
Triangulo3 ................................................................................................................................. 10
Triangulo4 ................................................................................................................................. 11
Rombo ............................................................................................................................................ 12
códigos de triángulos y rombo ........................................................................................... 12
triangulo1 ................................................................................................................................. 12
triangulo 2............................................................................................................................... 13
Triangulo3 ................................................................................................................................. 13
triangulo4 ................................................................................................................................. 14
Rombo ............................................................................................................................................ 15
Operaciones entre matrices y escalar por vector ............................................................................. 15
Código en modo texto ................................................................................................................... 15
Producto por escalar ................................................................................................................. 16
producto punto ......................................................................................................................... 16
suma de matrices ...................................................................................................................... 18
Producto cruz entre matrices .................................................................................................... 20
Código en modo grafico de operaciones entre vectores .................................................................. 22
Producto por escalar y producto punto ...................................................................... 22
suma de matrices .................................................................................................................... 29
Producto entre matrices .................................................................................................... 40

Procedimiento con lineas

Líneas oblicuas
(x,y)

Procedimiento lineasOblic1Rec (enteros n, x, y, delta)


Variables:
Enteros posy, posx
Inicio
si n>0 entonces
posx=x+delta
posy=y+delta
línea (x, posy, posx, y)
lineasOblic1 (n-1, x, y, delta)
Fin

Seguimiento
HACER SEGUIMIENTO (
x=10 y=20 posx=x+delta posy=y+delta delta=15 n=5
lienasOblicRec(10,20,25,35,15,5) linea(10, 25, 35, 20)
lineasOblicRec(10,20,40,50,15,4) línea(10, 40, 50, 20)
lineasOblicRec(10,20,55,65,15,3) línea(10, 55, 65, 20)
lineasOblicRec(10,20,70,80,15,2) línea(10, 70, 80, 20)
lineasOblicRec(10,20,85,95,15,1) línea(10, 85, 95, 20)

lienas oblicuas 2

procedimiento lineasOblic2Rec (enteros n, x, y, delta)


variables
enteros xfinal, yfinal
Inicio
si n>0 entonces
xfinal= x+ n*delta
yfnial=y+ n*delta
línea(x, yfinal, xfinal,y)
lineasOblic2(n-1, x+delta, y+delta, delta)
fin

Seguimiento2
Definamos los siguientes valores
x=10 y=20 posx=x+delta posy=y+delta delta=15 n=5
lienasOblic2Rec(10,20,25,35,15,5) linea(10, 25, 35, 20)
lineasOblic2Rec(10,20,40,50,15,4) línea(10, 40, 50, 20)
lineasOblic2Rec(10,20,55,65,15,3) línea(10, 55, 65, 20)
lineasOblic2Rec(10,20,70,80,15,2) línea(10, 70, 80, 20)
lineasOblic2Rec(10,20,85,95,15,1) línea(10, 85, 95, 20)

Lienas oblicuas 3

Procedimiento lineasOblic3Rec (entero n, x, y, delta)


Variables
Enteros: xfinal, yfinal
Inicio
Si n>0 entonces
yfinal=y+ n*delta
linea (x, y, xfinal, yfinal)
lineasOblic3Rec(n-1, x, y+delta, delta)
Seguimiento3
Definamos los siguientes valores
x=10 y=20 posx=x+delta posy=y+delta delta=15 n=5
lienasOblic2Rec(10,20,25,35,15,5) linea(10, 25, 35, 20)
lineasOblic2Rec(10,20,40,50,15,4) línea(10, 40, 50, 20)
lineasOblic2Rec(10,20,55,65,15,3) línea(10, 55, 65, 20)
lineasOblic2Rec(10,20,70,80,15,2) línea(10, 70, 80, 20)
lineasOblic2Rec(10,20,85,95,15,1) línea(10, 85, 95, 20)
Lineas oblicuas 4

Procedimiento líneaOblic4Rec (entero n, x, y, delta)


Variables
Enteros xfinal, yfinal
Inicio
Si n>0 entonces
xfinal= x+ n*delta
yfinal=y+ n*delta
línea (x, y, xfinal, yfinal)
lineasOblic4Rec (n-1, x+delta, y, delta)

Seguimiento4
Definamos los siguientes valores
x=10 y=20 posx=x+delta posy=y+delta delta=15 n=5
lienasOblic2Rec(10,20,25,35,15,5) linea(10, 25, 35, 20)
lineasOblic2Rec(10,20,40,50,15,4) línea(10, 40, 50, 20)
lineasOblic2Rec(10,20,55,65,15,3) línea(10, 55, 65, 20)
lineasOblic2Rec(10,20,70,80,15,2) línea(10, 70, 80, 20)
lineasOblic2Rec(10,20,85,95,15,1) línea(10, 85, 95, 20)
Procedimiento estrella
Estrella
Procedimiento líneas(entero n, x, y, delta)
Variables
Entero posx, posy, i
Inicio
xfinal=x+n*delta
yfinal=y+n*delta
para i=0 hasta (n-1) hacer
posx=x+i*delta
posy=y+(i+1)*delta
línea(posx, y, xfinal, posy)
posx=0
posy=0
para i=0 hasta (n-1) hacer
posx=x+(n-1-i)*delta
posy=y+i*delta
línea(xfinal, posy, posx, yfinal)
posx=0
posy=0
para i=0 hasta (n-1) hacer
posx=x+(n-i)*delta
posy=y+(n-1-i)*delta
línea(posx, yfinal, x, posy)
posx=0
posy=0
para i=0 hasta(n-1) hacer
posx=x +(n-i)*delta
posy=y+(i+1)*delta
línea(x, posy, posx, y)
fin

Pseudocódigo triángulos y rombo


Triangulo1

Constantes
Símbolo =”*”
Enteros n, i
Inicio
n=0
mientras n<1 hacer
n=leer(“ingrese un numero positivo mayor que 0”)
si n<1 hacer
escribir(“ingrese datos correctos”)
n=4
tri_1=0

para i=1 hasta n hacer


tri_1=simbolo*(i+1)
escribir(tri_1)
fin

Triangulo2

Constantes
Símbolo =”*”
Espacio=” “
Enteros n, i
Inicio

n=0
mientras n<1 hacer
n=leer(“ingrese un numero positivo mayor que 0”)
si n<1 hacer
escribir(“ingrese datos correctos”)
n=4
para i=1 hasta n hacer
tri_2=(n-i-1)*espacio+simbolo*(i+1)
escribir(tri_2)
fin

Triangulo3

constantes
cad= “*”
enteros: n, i
Inicio
n=0
mientras n<1 hacer
n=leer(“ingresar un numero entero positivo”)
si n<1 entonces
escribir(“ingrese los datos correctos”)
n=4
para i=1 hasta n hacer
tri_3=cad*(n-i)
escribir(tri_3)
fin

Triangulo4
Constantes
Símbolo =”*”
Espacio=” “
Enteros n, i
Inicio

n=0
mientras n<1 hacer
n=leer(“ingrese un entero positivo”)
si n<1 hacer
escribir(“ingrese datos correctos”)
n=4
para i=1 hasta n hacer
tri_4=esp*i+cad*(n-i)
escribir(tri_4)
fin
Rombo
Constantes
cad =”*”
esp=” “
Enteros n, i, j
Inicio
n=0
mientras n<1 hacer
n=leer(“ingrese un entero positivo”)
si n<1 entonces
escribir(“ingrese los valores correctos”)
n=4
romboS
para i=1 hasta n hacer
romboS=esp*(n-i)+cad*(2*i+1)
imprimir(romboS)
para j=1 hasta (n-1) hacer
romboI=esp*(j+2)+cad*(2*(n-j)-3)
escribir(romboI)
fin

códigos de triángulos y rombo


triangulo1
n=0
while n<1:
n= int(input("ingrese un numero positivo: "))
if n<1:
print("ingrese un valor correcto")

cad='*'
for i in range(n):
tri_1=cad*(i+1)
print(tri_1)

triangulo 2
n=0
while n<1:
n= int(input("ingrese un numero positivo: "))
if n<1:
print("ingrese un valor correcto")

cad='*'
esp=' '

for j in range(n):
tri_2=(n-j-1)*esp+cad*(j+1)
print(tri_2)

Triangulo3
n=0
while n<1:
n= int(input("ingrese un numero positivo: "))
if n<1:
print("ingrese un valor correcto")

cad='*'

for i in range(n):
tri_3=cad*(n-i)
print(tri_3) n=0
while n<1:
n= int(input("ingrese un numero positivo: "))
if n<1:
print("ingrese un valor correcto")

cad='*'

for i in range(n):
tri_3=cad*(n-i)
print(tri_3)

triangulo4
n=0
while n<1:
n=int(input("ingresar un valor enero positivo para n: "))
if n<1:
print("ingrese los valores correctos")
cad='*'
esp=' '

for i in range(n):
tri_4=esp*i+cad*(n-i)
print(tri_4)

Rombo
n=0
while n<1:
n=int(input("ingrese un entero positivo para n:"))
if n<1:
print("ingrese los datos correctos")

esp=' '
cad='*'
for i in range(n):
romboS=esp*(n-i)+cad*(2*i+1)
print(romboS)
for j in range(n-1):
romboI=esp*(j+2)+cad*(2*(n-j)-3)
print(romboI)

Operaciones entre matrices y escalar por vector

Código en modo texto


Producto por escalar
import numpy as np
print("producto escalar por vector")

def leerVecReal(n):
vecV= np.zeros(n)
for i in range (n):
vecV[i]=float(input("Ingrese el {}-ésimo elemento:
".format(i+1)))
return vecV

if __name__ == '__main__':
k=float(input("Ingrese el escalar real: "))
num=0
while num<=0:
num=int(input("Ingrese el número de elementos del vector:
"))
if num<=0:
print("El número debe ser mayor a cero.")
vecA= leerVecReal(num)
prod= k * vecA
print("{} x [{}]= [{}]".format(k,vecA,prod))

producto punto
import numpy as np
print("Producto punto entre 2 vectores")
def leerVecReal(n):
vecV=np.zeros(n)
for i in range(n):
vecV[i]=float(input("Ingrese el elemento de la
posicion {} del vector: ".format(i+1)))
return vecV
def prodPunto(vecA,vecB):
s=vecA.size
t=vecB.size
if s==t:
sum=0
for i in range(s):
prod=vecA[i]*vecB[i]
sum=sum+prod
return sum
else:
return ("Error, A y B deben tener mismo número de
elementos.")
if __name__ == '__main__':
a=0
b=0
while a<=0:
a=int(input("Ingrese el número de elementos del
vector A: "))
if a<=0:
print("El número debe ser mayor a cero: ")
else:

while b<=0:
b=int(input("Ingrese el número de elementos
del vector B: "))
if b<=0:
print("El número debe ser mayor a cero.")
vecA= leerVecReal(a)
print("vecA=",vecA)
vecB= leerVecReal(b)
print("vecB=",vecB)
prod= prodPunto(vecA,vecB)
print("Producto punto de A y B: ",prod)

suma de matrices
import numpy as np
print("Suma de matrices.")
def leerMatReal(n, m, nombre='mat'):
mat = np.zeros((n, m))
for i in range(n):
for j in range(m):
mat[i, j] = float(input(nombre+'[{},
{}] = '.format(i+1, j+1)))
return mat

def sumMat(matA,matB):
a=np.shape(matA) # np.shape da respectivamente el número
de filas y columnas
b=np.shape(matB)
if a==b:
MatSum=np.zeros((len(matA),len(matA[0])))
for i in range(len(matA)):
for j in range(len(matA[0])):
MatSum[i][j]=matA[i][j]+ matB[i][j]
return MatSum
else:
return "Error, debe coincidir el número de filas y
columnas."

if __name__ == '__main__':
a=0
b=0
c=0
d=0
while a<=0 or b<=0:
a=int(input("Ingrese el número de filas de A: "))
b=int(input("Ingrese el número de columnas de A: "))
if a<=0 or b<=0:
print("Deben ser mayores a cero.")
else:
while c<=0 or d<=0:
c=int(input("Ingrese el número de filas de B:
"))
d=int(input("Ingrese el número de columnas de
B: "))
if c<=0 or d<=0:
print("Deben ser mayor a cero.")
matA=leerMatReal(a,b,nombre='matA')
matB=leerMatReal(c,d,nombre='matB')
s=sumMat(matA,matB)
print("S=",(s))

Producto cruz entre matrices

import numpy as np
print("Producto de 2 matrices mxn")
a=0
b=0
c=0
d=0
while a<=0 or b<=0:
a=int(input("Ingrese el número de filas de A: "))
b=int(input("Ingrese el número de columnas de A: "))
if a<=0 or b<=0:
print("Deben ser mayores a cero.")
else:
while c<=0 or d<=0:
c=int(input("Ingrese el número de filas
de B: "))
d=int(input("Ingrese el número de
columnas de B: "))
if c<=0 or d<=0:
print("Deben ser mayores a
cero.")

def leerMatReal(n, m, nombre='mat'):


mat = np.zeros((n, m))
for i in range(n):
for j in range(m):
mat[i, j] = float(input(nombre+'[{},
{}] = '.format(i+1, j+1)))
return mat

def prodMat(matA,matB):
if b==c:
MatProd=np.zeros((len(matA),len(matB[0])))

for i in range(a):
for j in range(d):
for k in range(b):
MatProd[i][j]+=matA[i][k]*
matB[k][j]
return MatProd
else:
return "Error, debe coincidir el número de
columnas de A con el número de filas de B."

matA=leerMatReal(a,b,nombre='matA')
matB=leerMatReal(c,d,nombre='matB')
PRODUCTO=prodMat(matA,matB)
print(PRODUCTO)

Código en modo grafico de operaciones entre vectores

Producto por escalar y producto punto


from tkinter import *
from tkinter import ttk
import numpy as np
from tkinter import simpledialog
from tkinter import messagebox

class AplicacionPB():
def __init__(self):
self.ven0 = Tk()
self.ven0.geometry('500x350+200+80')
self.ven0.title('Operaciones con Vectores')
self.ven0.configure(background='light slate gray')
self.crearWidgets()
self.ven0.mainloop()
self.font=("consolas",12)

def crearWidgets(self):
self.tam = 0
self.esc = 1
self.indiceA = 1
self.indiceB = 1
self.btnIngresar = Button(self.ven0, text='Ingresar tamaño del
vector', command=self.nuevoTam)
self.btnIngresar.grid(row=0, column=0, columnspan=2, pady=5)

#########################################################################
########################################################
self.frmVecA = LabelFrame(self.ven0, text='Vector A:')

self.frmVecA.grid(row=1, column=0, padx=10, pady=10, sticky =


W+E)
self.lblTamañoA = Label(self.frmVecA,text='Tamaño del vector:
{}'.format(self.tam))
self.lblTamañoA.grid(row=0,column=0,columnspan=3, padx=5,pady=5)
self.lblCompA = Label(self.frmVecA, text='No hay
componententes.')
self.lblCompA.grid(row=1, column=0,padx=5,pady=5)
self.frmVecB = LabelFrame(self.ven0, text='Vector B:')
self.frmVecB.grid(row=1, column=1, padx=10, pady=10, sticky =
W+E)

self.lblTamañoB = Label(self.frmVecB,text='Tamaño del vector:


{}'.format(self.tam))
self.lblTamañoB.grid(row=0,column=0,columnspan=3, padx=5,pady=5)
self.lblCompB = Label(self.frmVecB, text='No hay componentes.')
self.lblCompB.grid(row=1, column=0,padx=5,pady=5)

def nuevoTam(self):
tam = simpledialog.askinteger(title = 'Tamaño del vector',prompt
= "Ingrese el tamaño del vector: ",

initialvalue =
'{}'.format(self.tam))
if not tam is None:
if tam > 0:
self.tam = tam
self.vecA = np.zeros(self.tam)
self.vecB = np.zeros(self.tam)
self.vecRes = np.zeros(self.tam)
self.vecRES = np.zeros(self.tam)
self.vecPro = np.zeros(self.tam)

self.lblTamañoA.configure(text = 'Tamaño del


Vector:{:4}'.format(self.tam))
self.lblTamañoB.configure(text = 'Tamaño del
Vector:{:4}'.format(self.tam))
self.lblCompA.configure(text='{}-ésima componente:
'.format(self.indiceA))

self.txtCompA = ttk.Entry(self.frmVecA, width=8)


self.txtCompA.grid(row=1, column=2, padx=5,pady=5)

self.lblCompB.configure(text='{}-ésima componente:
'.format(self.indiceB))
self.txtCompB = ttk.Entry(self.frmVecB, width=8)
self.txtCompB.grid(row=1, column=2, padx=5,pady=5)
self.btnGuardarA = Button(self.frmVecA,
text='Guardar',command=self.guardarA)
self.btnGuardarA.grid(row=2, column=0,
columnspan=3,padx=5,pady=5)

self.btnGuardarB = Button(self.frmVecB,
text='Guardar',command=self.guardarB)
self.btnGuardarB.grid(row=2, column=0,
columnspan=3,padx=5,pady=5)

#########################################################################
#################################################
self.frmOper = LabelFrame(self.ven0, text='Operaciones:')
self.frmOper.grid(row=2, column=0,rowspan=2, padx=10,
pady=10, sticky = W+E)
self.lblEsc = Label(self.frmOper, text='Escalar:
{}'.format(self.esc))
self.lblEsc.grid(row=0, column=0,padx=5,pady=5)

self.btnCam = Button(self.frmOper, text='Cambiar


escalar', command=self.nuevoesc)
self.btnCam.grid(row=0, column=1,padx=5,pady=5)
self.lblPunto = Label(self.frmOper, text="Producto
punto")
self.lblPunto.grid(row=1, column=0)
self.btnPunto = Button(self.frmOper, text='A * B',
command=self.proPunto)

self.btnPunto.grid(row=1,
column=1,columnspan=2,padx=5,pady=5)
self.lblEscA = Label(self.frmOper, text="Escalar por A")
self.lblEscA.grid(row=2, column=0)
self.btnEscA = Button(self.frmOper, text='{} x
A'.format(self.esc),command=self.escalarA)
self.btnEscA.grid(row=2, column=1,padx=5,pady=5)
self.lblEscB = Label(self.frmOper, text="Escalar por B")
self.lblEscB.grid(row=3, column=0)

self.btnEscB = Button(self.frmOper, text='{} x


B'.format(self.esc),command=self.escalarB)
self.btnEscB.grid(row=3, column=1,padx=5,pady=5)

#########################################################################
###############################################

self.frmRtas = LabelFrame(self.ven0, text="Resultados")

self.frmRtas.grid(row=2, column=1, padx=10, pady=10,


sticky=W+E)
self.lblVecPro= Label(self.frmRtas, text="")
self.lblVecPro.grid(row=3, column=0)
self.lblVecRES = Label(self.frmRtas, text='')

self.lblVecRES.grid(row=4,column=0,columnspan=4,
padx=5,pady=5)
self.lblVecRes = Label(self.frmRtas, text='')
self.lblVecRes.grid(row=5,column=0,columnspan=4,
padx=5,pady=5)
else:
messagebox.showerror(message = 'El número debe ser
positivo.',title = 'Error')

def guardarA(self):
cadComp = self.txtCompA.get()
if cadComp:
try:
comp = float(cadComp)
error = False
except ValueError:
messagebox.showerror(title='Error', message='Error en la
entrada.')
error = True

if not error and self.indiceA < self.tam+1:


self.vecA[self.indiceA-1] = comp
self.indiceA = self.indiceA + 1
self.lblCompA.configure(text='{}-ésima componente:
'.format(self.indiceA))
self.txtCompA = ttk.Entry(self.frmVecA, width=8)

self.txtCompA.grid(row=1, column=2, padx=5,pady=5)


if self.indiceA == self.tam+1:
self.lblCompA.configure(text='Vector Completo')
self.txtCompA = ttk.Entry(self.frmVecA, width=8)
self.txtCompA.grid(row=1, column=2, padx=5,pady=5)

def guardarB(self):
cadCompB = self.txtCompB.get()
if cadCompB:
try:
compB = float(cadCompB)
errorB = False
except ValueError:

messagebox.showerror(title='Error', message='Error en la
entrada.')
errorB = True

if not errorB and self.indiceB < self.tam+1:


self.vecB[self.indiceB-1] = compB
self.indiceB = self.indiceB + 1

self.lblCompB.configure(text='{}-ésima componente:
'.format(self.indiceB))
self.txtCompB = ttk.Entry(self.frmVecB, width=8)
self.txtCompB.grid(row=1, column=2, padx=5,pady=5)
if self.indiceB == self.tam+1:
self.lblCompB.configure(text='Vector Completo')
self.txtCompB = ttk.Entry(self.frmVecA, width=8)
self.txtCompB.grid(row=1, column=2, padx=5,pady=5)
#########################################################################
##########################################

def proPunto(self): #Calcula el producto punto de los 2 vectores


ingresados
suma = 0
for i in range(self.tam):
suma = suma + self.vecA[i] * self.vecB[i]
self.lblVecPro.configure(text='A * B = {}'.format(suma))

def nuevoesc(self): #Pide el escalar real


esc = simpledialog.askfloat(title = 'Escalar', prompt = 'Ingrese
el Escalar: ',initialvalue = '{}'.format(self.esc))
if not esc is None:
self.esc = esc
self.lblEsc.configure(text='Escalar: {}'.format(self.esc))
self.btnEscA.configure(text='{} x A'.format(self.esc))
self.btnEscB.configure(text='{} x B'.format(self.esc))
def escalarA(self):
for i in range (self.tam):
self.vecRES[i] = self.esc * self.vecA[i]
self.lblVecRES.configure(text='{} x A =
{}'.format(self.esc,self.vecRES))

def escalarB(self):
for i in range (self.tam):
self.vecRes[i] = self.esc * self.vecB[i]
self.lblVecRes.configure(text='{} x B =
{}'.format(self.esc,self.vecRes))

if __name__ == '__main__':
miApp = AplicacionPB()

suma de matrices
from tkinter import *
from tkinter import ttk
import numpy as np
from tkinter import simpledialog
from tkinter import messagebox
class Aplicacion():
def __init__(self):
self.raiz = Tk()
#self.raiz.geometry('1000x500+50+50')
self.raiz.title('Suma de matrices A y B')
self.fuente = ('Courier',14)
self.crearWidgets()
self.raiz.mainloop()

def crearWidgets(self):
self.fil1 = self.col1 = self.fil2 = self.col2 = 5
self.ind11 = self.ind12 = self.ind21 = self.ind22 = 1

self.mA = np.zeros((self.fil1, self.fil1))


self.mB = np.zeros((self.fil1, self.fil1))
self.mAB = np.zeros((self.fil1, self.fil1))

self.frmA = LabelFrame(self.raiz, text = 'Matrir A',


font=self.fuente)
self.frmA.grid(row = 0, column = 0, padx = 3,pady = 3, ipadx=3,
ipady = 3)

self.lblTam = Label(self.frmA, text = 'Tamaño de matriz :{:2}*{}


'.format(self.fil1,self.fil1),font=self.fuente)
self.lblTam.grid(row=0, column=0, sticky = W, columnspan=2)

self.btnTam = Button(self.frmA, text='Tamaño', font=self.fuente,


command=lambda:self.nuevoTam(0), borderwidth=5)
self.btnTam.grid(row=0, column=2, sticky='WE')
self.frmD1 = LabelFrame(self.frmA, text = 'Posicion y Valor',
font=self.fuente)

self.frmD1.grid(row = 1, column = 0, padx = 3,pady = 3, ipadx=3,


ipady = 3)

Label(self.frmD1, text = 'Fil:', font=self.fuente).grid(row=0,


column=0, sticky = W)
self.txtFil1 = ttk.Entry(self.frmD1, width = 3, font=self.fuente)
self.txtFil1.grid(row=0, column=1,sticky = W)
self.txtFil1.focus()

Label(self.frmD1, text = 'Col:', font=self.fuente).grid(row=0,


column=2, sticky = W)
self.txtCol1 = ttk.Entry(self.frmD1, width = 3, font=self.fuente)
self.txtCol1.grid(row=0, column=3,sticky = W)

Label(self.frmD1, text = 'Valor:', font=self.fuente).grid(row=2,


column=0, sticky = W)

self.txtNum = ttk.Entry(self.frmD1, width = 5, font=self.fuente)


self.txtNum.grid(row=2, column=1, sticky = W)

self.btnGuardar = Button(self.frmA, text='Guardar',


font=self.fuente,
command=lambda:self.guardar(0),
borderwidth=5)
self.btnGuardar.grid(row=1, column=2, rowspan=2, sticky='WE')

##############################################################

self.frmB = LabelFrame(self.raiz, text = 'Matrir B',


font=self.fuente)
self.frmB.grid(row = 0, column = 1, padx = 3,pady = 3, ipadx=3,
ipady = 3)

self.lblTam1 = Label(self.frmB, text = 'Tamaño de matriz :{:2}*{}


'.format(self.fil1,self.fil1),font=self.fuente)
self.lblTam1.grid(row=0, column=0, sticky = W, columnspan=2)
self.btnTam1 = Button(self.frmB, text='Tamaño', font=self.fuente,
command=lambda:self.nuevoTam(1), borderwidth=5)
self.btnTam1.grid(row=0, column=2, sticky='WE')

#Label(self.frmV, text = 'Posicion:',


font=self.fuente).grid(row=1, column=0, sticky = W)

self.frmD2 = LabelFrame(self.frmB, text = 'Posicion y Valor',


font=self.fuente)
self.frmD2.grid(row = 1, column = 0, padx = 3,pady = 3, ipadx=3,
ipady = 3)

Label(self.frmD2, text = 'Fil:', font=self.fuente).grid(row=0,


column=0, sticky = W)
self.txtFil2 = ttk.Entry(self.frmD2, width = 3, font=self.fuente)
self.txtFil2.grid(row=0, column=1,sticky = W)

Label(self.frmD2, text = 'Col:', font=self.fuente).grid(row=0,


column=2, sticky = W)
self.txtCol2 = ttk.Entry(self.frmD2, width = 3, font=self.fuente)
self.txtCol2.grid(row=0, column=3,sticky = W)

Label(self.frmD2, text = 'Valor:', font=self.fuente).grid(row=2,


column=0, sticky = W)

self.txtNum1 = ttk.Entry(self.frmD2, width = 5, font=self.fuente)


self.txtNum1.grid(row=2, column=1, sticky = W)
self.btnGuardar1 = Button(self.frmB, text='Guardar',
font=self.fuente,

command=lambda:self.guardar(1),
borderwidth=5)
self.btnGuardar1.grid(row=1, column=2, rowspan=2, sticky='WE')

#######

self.frmVisualizar = LabelFrame(self.raiz, text = 'Acciones',


font=self.fuente)

self.frmVisualizar.grid(row=2,column = 0, columnspan = 2,
padx=15,pady = 3)

self.lblIndice1 = Label(self.frmVisualizar, text = 'A[{},{}] =


{}'.format(self.ind11,self.ind11,self.mA[0,0]),
font=self.fuente)
self.lblIndice1.grid(row=0, column=0, padx=10, pady=10, sticky=W)

##########
self.lblSalidaA =
Label(self.frmVisualizar,text=self.matrizStr(self.mA, 'A'),
font=self.fuente)
self.lblSalidaA.grid(row=1, column=0, padx=3, pady=3, ipadx=3,
ipady = 30)

self.lblSalidaB =
Label(self.frmVisualizar,text=self.matrizStr(self.mB, 'B'),
font=self.fuente)
self.lblSalidaB.grid(row=1, column=4, padx=3, pady=3, ipadx=3,
ipady = 30, sticky=W+E, columnspan=4)
self.lblSalidaAB =
Label(self.frmVisualizar,text=self.matrizStr(self.mAB, 'A + B'),
font=self.fuente)
self.lblSalidaAB.grid(row=1, column=8, padx=3, pady=3, ipadx=3,
ipady = 30, sticky=W+E, columnspan=4)

################

self.btnSumaAB = Button(self.frmVisualizar, text='Sumar matrices


(A + B)', font=self.fuente,
command=self.sumarAB, borderwidth=5)

self.btnSumaAB.grid(row=2, column=0, padx=10, pady=10,


sticky='WE')
self.btnSalir = Button(self.frmVisualizar, text='Salir',
font=self.fuente,
command=self.cerrar, borderwidth=5)

self.btnSalir.grid(row=2, column=6, padx=10, pady=10,


sticky='WE')

def matrizStr(self, M, nombre = 'm'):


fil = M.shape[0]
col = M.shape[1]

cad = ''
for i in range(fil):
for j in range(col):
cad = '{} {:^4}'.format(cad, str(M[i][j]))

cad = '{:^4} {}'.format(cad, '\n\n')


return cad

def nuevoTam(self, args):


# Actualiza el tamaño del vector e inicializa el vector con ceros
if args == 0:

f = simpledialog.askinteger(title = 'Filas', prompt= 'Ingrese


# de filas para A', initialvalue = '{}'.format(5))
c = simpledialog.askinteger(title = 'Colunnas', prompt=
'Ingrese # de colunas para A',
initialvalue = '{}'.format(5))
if not f is None and not c is None: # si se seleciona el
boton "OK" en askinteger.
if f > 0 and c>0:
self.fil1 = f
self.col1 = c
self.ind11 = self.ind12 = 1
self.mA = np.zeros((self.fil1, self.col1))

self.lblTam.configure(text = 'Tamaño de matriz


:{:2}*{} '.format(self.fil1,self.col1))
self.lblIndice1.configure(text = 'A[{},{}] =
{}'.format(self.ind11,self.ind11,self.mA[0,0]))

self.lblSalidaA.configure(text =
self.matrizStr(self.mA, 'A'))
else:
messagebox.showerror(message="El número debe ser
positivo", title="Error")
self.txtFil1.focus()

if args == 1:
f = simpledialog.askinteger(title = 'Filas', prompt= 'Ingrese
# de filas para B',
initialvalue = '{}'.format(5))

c = simpledialog.askinteger(title = 'Colunnas', prompt=


'Ingrese # de colunas para B',
initialvalue = '{}'.format(5))

if not f is None and not c is None: # si se seleciona el


boton "OK" en askinteger.
if f > 0 and c>0:
self.fil2 = f
self.col2 = c
self.ind21 = self.ind22 = 1
self.mB = np.zeros((self.fil2, self.col2))
self.lblTam1.configure(text = 'Tamaño de matriz
:{:2}*{} '.format(self.fil2,self.col2))
self.lblIndice1.configure(text = 'B[{},{}] =
{}'.format(self.ind21,self.ind22,self.mB[0,0]))
self.lblSalidaB.configure(text =
self.matrizStr(self.mB, 'B'))
else:
messagebox.showerror(message="El número debe ser
positivo", title="Error")
self.txtFil2.focus()

fil1 = self.mA.shape[0]
col1 = self.mA.shape[1]
fil2 = self.mB.shape[0]
col2 = self.mB.shape[1]

if fil1 == fil2 and col1 == col2:


self.mAB = np.zeros((self.fil1, self.col1))

self.lblSalidaAB.configure(text = self.matrizStr(self.mAB,'A
+ B'))
def guardar(self, args):
if args == 0:
cadF = self.txtFil1.get()
cadC = self.txtCol1.get()
cadNum = self.txtNum.get()

if cadF and cadC and cadNum:


try:
f = int(cadF)
c = int(cadC)
num = float(cadNum)
if (f < 1 or f > self.fil1) or (c < 1 or c >
self.col1) :
messagebox.showerror(message="Filas y/o colunas
fuera de rango", title="Error")
error = True
else:
error = False
except ValueError:

messagebox.showerror(message="Error en la entrada",
title="Error")
error = True

if not error:
self.ind11 = f
self.ind12 = c
self.mA[self.ind11-1][self.ind12-1] = num
self.lblIndice1.configure(text = 'A[{},{}] =
{}'.format(self.ind11,self.ind12,self.mA[self.ind11-1][self.ind12-1]))
self.lblSalidaA.configure(text =
self.matrizStr(self.mA, 'A'))
self.txtFil1.focus()

if args == 1:
cadF = self.txtFil2.get()
cadC = self.txtCol2.get()
cadNum = self.txtNum1.get()

if cadF and cadC and cadNum:


try:
f = int(cadF)
c = int(cadC)
num = float(cadNum)

if (f < 1 or f > self.fil2) or (c < 1 or c >


self.col2) :
messagebox.showerror(message="Filas y/o colunas
fuera de rango", title="Error")
error = True
else:
error = False
except ValueError:
messagebox.showerror(message="Error en la entrada",
title="Error")
error = True

if not error:
self.ind21 = f
self.ind22 = c
self.mB[self.ind21-1][self.ind22-1] = num
self.lblIndice1.configure(text = 'B[{},{}] =
{}'.format(self.ind21,self.ind22,self.mB[self.ind21-1][self.ind22-1]))

self.lblSalidaB.configure(text =
self.matrizStr(self.mB, 'B'))
self.txtFil2.focus()

def sumarAB(self):
fil1 = self.mA.shape[0]
col1 = self.mA.shape[1]
fil2 = self.mB.shape[0]
col2 = self.mB.shape[1]

if fil1 == fil2 and col1 == col2:


for i in range(fil1):
for j in range(col1):
self.mAB[i][j] = self.mA[i][j] + self.mB[i][j]

self.lblSalidaAB.configure(text = self.matrizStr(self.mAB,'A
+ B'))
else:
messagebox.showerror(message="Las matrices A y B no tienen la
misma dimesion", title="Error")

def cerrar(self):
self.raiz.destroy()

'''def inicio(self):
self.ind = 1
self.lblIndice.configure(text = 'v[{}] =
{}'.format(self.ind,self.vecV[self.ind-1]))
def anterior(self):
if self.ind > 1:
self.ind=self.ind-1
self.lblIndice.configure(text = 'v[{}] =
{}'.format(self.ind,self.vecV[self.ind-1]))

def siguiente(self):
if self.ind < self.tam:
self.ind = self.ind + 1
self.lblIndice.configure(text = 'v[{}] =
{}'.format(self.ind,self.vecV[self.ind-1]))

def final(self):
self.ind = self.tam
self.lblIndice.configure(text = 'v[{}] =
{}'.format(self.ind,self.vecV[self.ind-1]))'''

if __name__ == '__main__':
miApp = Aplicacion()

Producto entre matrices


from tkinter import *
from tkinter import ttk
import numpy as np
from tkinter import simpledialog
from tkinter import messagebox

class Aplicacion():
def __init__(self):
self.raiz = Tk()
#self.raiz.geometry('1000x500+50+50')
self.raiz.title('Producto de matrices A y B')
self.fuente = ('Courier',14)
self.crearWidgets()
self.raiz.mainloop()

def crearWidgets(self):
self.fil1 = self.col1 = self.fil2 = self.col2 = 5
self.ind11 = self.ind12 = self.ind21 = self.ind22 = 1

self.mA = np.zeros((self.fil1, self.fil1))


self.mB = np.zeros((self.fil1, self.fil1))
self.mAB = np.zeros((self.fil1, self.col2))

self.frmA = LabelFrame(self.raiz, text = 'Matrir A',


font=self.fuente)
self.frmA.grid(row = 0, column = 0, padx = 3,pady = 3,
ipadx=3, ipady = 3)
self.lblTam = Label(self.frmA, text = 'Tamaño de matriz
:{:2}*{} '.format(self.fil1,self.fil1),font=self.fuente)
self.lblTam.grid(row=0, column=0, sticky = W,
columnspan=2)
self.btnTam = Button(self.frmA, text='Tamaño',
font=self.fuente, command=lambda:self.nuevoTam(0), borderwidth=5)
self.btnTam.grid(row=0, column=2, sticky='WE')

self.frmD1 = LabelFrame(self.frmA, text = 'Posicion y


Valor', font=self.fuente)
self.frmD1.grid(row = 1, column = 0, padx = 3,pady = 3,
ipadx=3, ipady = 3)

Label(self.frmD1, text = 'Fil:',


font=self.fuente).grid(row=0, column=0, sticky = W)
self.txtFil1 = ttk.Entry(self.frmD1, width = 3,
font=self.fuente)
self.txtFil1.grid(row=0, column=1,sticky = W)
self.txtFil1.focus()

Label(self.frmD1, text = 'Col:',


font=self.fuente).grid(row=0, column=2, sticky = W)
self.txtCol1 = ttk.Entry(self.frmD1, width = 3,
font=self.fuente)
self.txtCol1.grid(row=0, column=3,sticky = W)

Label(self.frmD1, text = 'Valor:',


font=self.fuente).grid(row=2, column=0, sticky = W)

self.txtNum = ttk.Entry(self.frmD1, width = 5,


font=self.fuente)
self.txtNum.grid(row=2, column=1, sticky = W)
self.btnGuardar = Button(self.frmA, text='Guardar',
font=self.fuente,
command=lambda:self.guardar(0),
borderwidth=5)
self.btnGuardar.grid(row=1, column=2, rowspan=2,
sticky='WE')

##############################################################

self.frmB = LabelFrame(self.raiz, text = 'Matrir B',


font=self.fuente)
self.frmB.grid(row = 0, column = 1, padx = 3,pady = 3,
ipadx=3, ipady = 3)

self.lblTam1 = Label(self.frmB, text = 'Tamaño de matriz


:{:2}*{} '.format(self.fil1,self.fil1),font=self.fuente)
self.lblTam1.grid(row=0, column=0, sticky = W,
columnspan=2)
self.btnTam1 = Button(self.frmB, text='Tamaño',
font=self.fuente, command=lambda:self.nuevoTam(1), borderwidth=5)
self.btnTam1.grid(row=0, column=2, sticky='WE')

self.frmD2 = LabelFrame(self.frmB, text = 'Posicion y


Valor', font=self.fuente)
self.frmD2.grid(row = 1, column = 0, padx = 3,pady = 3,
ipadx=3, ipady = 3)
Label(self.frmD2, text = 'Fil:',
font=self.fuente).grid(row=0, column=0, sticky = W)
self.txtFil2 = ttk.Entry(self.frmD2, width = 3,
font=self.fuente)
self.txtFil2.grid(row=0, column=1,sticky = W)

Label(self.frmD2, text = 'Col:',


font=self.fuente).grid(row=0, column=2, sticky = W)
self.txtCol2 = ttk.Entry(self.frmD2, width = 3,
font=self.fuente)
self.txtCol2.grid(row=0, column=3,sticky = W)

Label(self.frmD2, text = 'Valor:',


font=self.fuente).grid(row=2, column=0, sticky = W)

self.txtNum1 = ttk.Entry(self.frmD2, width = 5,


font=self.fuente)
self.txtNum1.grid(row=2, column=1, sticky = W)

self.btnGuardar1 = Button(self.frmB, text='Guardar',


font=self.fuente,
command=lambda:self.guardar(1),
borderwidth=5)
self.btnGuardar1.grid(row=1, column=2, rowspan=2,
sticky='WE')

#######

self.frmVisualizar = LabelFrame(self.raiz, text =


'Acciones', font=self.fuente)
self.frmVisualizar.grid(row=2,column = 0, columnspan = 2,
padx=15,pady = 3)

self.lblIndice1 = Label(self.frmVisualizar, text =


'A[{},{}] = {}'.format(self.ind11,self.ind11,self.mA[0,0]),
font=self.fuente)
self.lblIndice1.grid(row=0, column=0, padx=10, pady=10,
sticky=W)

##########
self.lblSalidaA =
Label(self.frmVisualizar,text=self.matrizStr(self.mA, 'A'),
font=self.fuente)
self.lblSalidaA.grid(row=1, column=0, padx=3, pady=3,
ipadx=3, ipady = 30)

self.lblSalidaB =
Label(self.frmVisualizar,text=self.matrizStr(self.mB, 'B'),
font=self.fuente)
self.lblSalidaB.grid(row=1, column=4, padx=3, pady=3,
ipadx=3, ipady = 30, sticky=W+E, columnspan=4)

self.lblSalidaAB =
Label(self.frmVisualizar,text=self.matrizStr(self.mAB, 'A + B'),
font=self.fuente)
self.lblSalidaAB.grid(row=1, column=8, padx=3, pady=3,
ipadx=3, ipady = 30, sticky=W+E, columnspan=4)

################
self.btnSumaAB = Button(self.frmVisualizar, text='Producto
de matrices (A * B)', font=self.fuente,
command=self.productoAB,
borderwidth=5)
self.btnSumaAB.grid(row=2, column=0, padx=10, pady=10,
sticky='WE')
self.btnSalir = Button(self.frmVisualizar, text='Salir',
font=self.fuente,
command=self.cerrar,
borderwidth=5)
self.btnSalir.grid(row=2, column=6, padx=10, pady=10,
sticky='WE')

def matrizStr(self, M, nombre = 'm'):


fil = M.shape[0]
col = M.shape[1]

cad = ''
for i in range(fil):
for j in range(col):
cad = '{} {:^4}'.format(cad, str(M[i][j]))

cad = '{:^4} {}'.format(cad, '\n\n')

return cad

def nuevoTam(self, args):


# Actualiza el tamaño del vector e inicializa el vector
con ceros
if args == 0:
f = simpledialog.askinteger(title = 'Filas', prompt=
'Ingrese # de filas para A', initialvalue = '{}'.format(5))
c = simpledialog.askinteger(title = 'Colunnas',
prompt= 'Ingrese # de colunas para A',
initialvalue = '{}'.format(5))
if not f is None and not c is None: # si se seleciona
el boton "OK" en askinteger.
if f > 0 and c>0:
self.fil1 = f
self.col1 = c
self.ind11 = self.ind12 = 1
self.mA = np.zeros((self.fil1, self.col1))
self.lblTam.configure(text = 'Tamaño de matriz
:{:2}*{} '.format(self.fil1,self.col1))
self.lblIndice1.configure(text = 'A[{},{}] =
{}'.format(self.ind11,self.ind11,self.mA[0,0]))
self.lblSalidaA.configure(text =
self.matrizStr(self.mA, 'A'))
else:
messagebox.showerror(message="El número debe
ser positivo", title="Error")
self.txtFil1.focus()

if args == 1:
f = simpledialog.askinteger(title = 'Filas', prompt=
'Ingrese # de filas para B',
initialvalue = '{}'.format(5))
c = simpledialog.askinteger(title = 'Colunnas',
prompt= 'Ingrese # de colunas para B',
initialvalue = '{}'.format(5))
if not f is None and not c is None: # si se seleciona
el boton "OK" en askinteger.
if f > 0 and c>0:
self.fil2 = f
self.col2 = c
self.ind21 = self.ind22 = 1
self.mB = np.zeros((self.fil2, self.col2))
self.lblTam1.configure(text = 'Tamaño de
matriz :{:2}*{} '.format(self.fil2,self.col2))
self.lblIndice1.configure(text = 'B[{},{}] =
{}'.format(self.ind21,self.ind22,self.mB[0,0]))
self.lblSalidaB.configure(text =
self.matrizStr(self.mB, 'B'))
else:
messagebox.showerror(message="El número debe
ser positivo", title="Error")
self.txtFil2.focus()

fil1 = self.mA.shape[0]
col1 = self.mA.shape[1]
fil2 = self.mB.shape[0]
col2 = self.mB.shape[1]

if col1 == fil2:
self.mAB = np.zeros((self.fil1, self.col2))
self.lblSalidaAB.configure(text =
self.matrizStr(self.mAB,'A + B'))
def guardar(self, args):
if args == 0:
cadF = self.txtFil1.get()
cadC = self.txtCol1.get()
cadNum = self.txtNum.get()

if cadF and cadC and cadNum:


try:
f = int(cadF)
c = int(cadC)
num = float(cadNum)
if (f < 1 or f > self.fil1) or (c < 1 or c >
self.col1) :
messagebox.showerror(message="Filas y/o
colunas fuera de rango", title="Error")
error = True
else:
error = False
except ValueError:
messagebox.showerror(message="Error en la
entrada", title="Error")
error = True

if not error:
self.ind11 = f
self.ind12 = c
self.mA[self.ind11-1][self.ind12-1] = num
self.lblIndice1.configure(text = 'A[{},{}] =
{}'.format(self.ind11,self.ind12,self.mA[self.ind11-1][self.ind12-
1]))
self.lblSalidaA.configure(text =
self.matrizStr(self.mA, 'A'))
self.txtFil1.focus()

if args == 1:
cadF = self.txtFil2.get()
cadC = self.txtCol2.get()
cadNum = self.txtNum1.get()

if cadF and cadC and cadNum:


try:
f = int(cadF)
c = int(cadC)
num = float(cadNum)
if (f < 1 or f > self.fil2) or (c < 1 or c >
self.col2) :
messagebox.showerror(message="Filas y/o
colunas fuera de rango", title="Error")
error = True
else:
error = False
except ValueError:
messagebox.showerror(message="Error en la
entrada", title="Error")
error = True
if not error:
self.ind21 = f
self.ind22 = c
self.mB[self.ind21-1][self.ind22-1] = num
self.lblIndice1.configure(text = 'B[{},{}] =
{}'.format(self.ind21,self.ind22,self.mB[self.ind21-1][self.ind22-
1]))
self.lblSalidaB.configure(text =
self.matrizStr(self.mB, 'B'))
self.txtFil2.focus()

def productoAB(self):
fil1 = self.mA.shape[0]
col1 = self.mA.shape[1]
fil2 = self.mB.shape[0]
col2 = self.mB.shape[1]

if col1 == fil2:
for i in range(fil1):
for j in range(col2):
acum = 0
for k in range(fil2):
acum = acum + self.mA[i][k]*self.mB[k][j]
self.mAB[i][j] = acum

self.lblSalidaAB.configure(text =
self.matrizStr(self.mAB,'A + B'))
else:
messagebox.showerror(message="Las columnas de A no es
igual a las filas de B", title="Error")

def cerrar(self):
self.raiz.destroy()

'''def inicio(self):
self.ind = 1
self.lblIndice.configure(text = 'v[{}] =
{}'.format(self.ind,self.vecV[self.ind-1]))

def anterior(self):
if self.ind > 1:
self.ind=self.ind-1
self.lblIndice.configure(text = 'v[{}] =
{}'.format(self.ind,self.vecV[self.ind-1]))

def siguiente(self):
if self.ind < self.tam:
self.ind = self.ind + 1
self.lblIndice.configure(text = 'v[{}] =
{}'.format(self.ind,self.vecV[self.ind-1]))

def final(self):
self.ind = self.tam
self.lblIndice.configure(text = 'v[{}] =
{}'.format(self.ind,self.vecV[self.ind-1]))'''
if __name__ == '__main__':
miApp = Aplicacion()

También podría gustarte