Documentos de Académico
Documentos de Profesional
Documentos de Cultura
OPCIONES:
2
ARREGLOS CON LISTAS
VECTORES CON LISTAS
Por ejemplo:
>>> v1=[1, 2, 3, 4]
>>> v1[0] # Elemento de la posición 0
1
def leev():
print("lee un vector:")
ne = int(input('Numero de elementos= '))
v=list(range(ne)) # crea el vector
for i in range(ne):
# i reemplaza a {0}:
v[i] = int(input(' elemento ({0}): '.format(i)))
return v
VECTORES CON LISTAS
def suma(v1, v2):
ne1=len(v1)
ne2=len(v2)
if ne1==ne2:
s=list(range(ne1)) # crea el vector
for i in range(ne1):
s[i] = v1[i] + v2[i]
print("suma:",s)
else:
print("no se suman, tamaños distintos")
def principal():
w1=leev();
w2=leev();
suma(w1, w2)
MATRIZ CON LISTAS
La matriz es, por ejemplo de 2 filas y 2 columnas:
>>> M=[ [1, 2], [3, 4] ]
>>> M[0] # Fila 0
[1, 2]
>>> M[1][0] # Fila 1, Columna 0
3
def mostrar_matriz(M):
print(‘\nMatriz’)
nf = len(M) # Número de filas
nc = len(M[0]) # Número de columnas
for f in range(nf):
for c in range(nc):
print(M[f][c],end='\t') # en la misma línea, tabulados
print('') # Salto de línea
MATRIZ CON LISTAS
# Producto de una matriz por un número
def producto(M, n):
nf = len(M) # Número de filas
nc = len(M[0]) # Número de columnas
for f in range(nf):
for c in range(nc):
M[f][c]= n*M[f][c]
return M
def principal2():
W=leer_matriz()
x=int(input(“Número= ”))
W=producto(W, x)
mostrar_matriz(W)
Numpy
NumPy = NumericalPython
• NumPy es el paquete fundamental para
computación científica con Python.
• Contiene:
– Arreglos N-dimensionales con métodos avanzados
– Funciones de algebra lineal
– Transformadas de Fourier
– Numeros random avanzados
– Herramientas para integración con código C/C++/
Fortran
NumPy documentación
• Documentación oficial
– http://docs.scipy.org/doc/
• Libro de NumPy
– http://web.mit.edu/dvp/Public/numpybook.pdf
• Ejemplos
– https://docs.scipy.org/doc/numpy/reference/routines.html
Arrays – Numerical Python (Numpy)
Las listas sirven para arreglos uni-dimensionales de pocos datos
>>> a = [1,3,5,7,9] >>> print(b[1][2:4])
>>> print(a[2:4]) [6, 8]
>>> a = [1,3,5,7,9]
[5, 7] >>> b = [3,5,6,7,9]
>>> b = [[1, 3, 5, 7, 9], [2, 4, 6, 8, 10]] >>> c = a + b
>>> print(b[0]) >>> print c
[1, 3, 5, 7, 9] [1, 3, 5, 7, 9, 3, 5, 6, 7, 9]
>>> x = np.array([1,2,3,4])
>>> y = x.copy()
>>> x is y
False
>>> id(x), id(y)
(139814289111920, 139814289111840)
>>> x[0] = 9
>>> x
array([9, 2, 3, 4])
>>> y
array([1, 2, 3, 4])
Numpy – array creación y uso
>>> a = np.arange(4.0)
>> a
array([0., 1., 2., 3.])
>>> b = a * 23.4
>>> b
array([ 0. , 23.4, 46.8, 70.2])
>>> c = b/(a+1)
>>> c += 10
>>> print c
[ 10. 21.7 25.6 27.55]
>>> arr = np.arange(100, 200)
>>> seleccion = [5, 25, 50, 75, -5]
>>> print(arr[seleccion]) #puede usar lista enteros como índices
[105, 125, 150, 175, 195]
Numpy – array creación y uso
>>> arr = np.arange(10, 20)
>> arr
array([10, 11, 12, 13, 14, 15, 16, 17, 18, 19])
>>> div_por_3 = arr%3 == 0 # comparación produce un
arreglo con dato boolean
>>> print(div_por_3)
[ False False True False False True False False True False]
>>> print(arr[div_por_3]) # puede usarse una lista boolean
como indices (considera los True)
[12 15 18]
# Cambiando las dimensiones con reshape
>>> arr = np.arange(10, 20) . reshape((2,5))
[[10 11 12 13 14]
[15 16 17 18 19]]
Numpy – métodos array
>>> arr.sum() # sumatoria
145
>>> arr.mean() # promedio
14.5
>>> arr.std() # desviación estándar
2.8722813232690143
>>> arr.max() # mayor
19
>>> arr.min() # menor
10
>>> div_by_3.all() # todos son True
False
>>> div_by_3.any() # alguno es True
True
>>> div_by_3.sum() # sumatoria (No.) de True
3
>>> div_by_3.nonzero() # posiciones de True
(array([2, 5, 8]), dtype=int64),)
Numpy – métodos array - sorting
• Ver http://numpy.scipy.org
Funciones NumPy
abs() min()
exp() max()
… multiply(arr,num)
add() polyfit()
binomial() randint()
cumprod() transpose()
cumsum() …
floor()
histogram()
29
Numpy – operaciones array
>>> a = np.array([[1.0, 2.0], [4.0, 3.0]])
>>> print(a)
[[ 1. 2.]
[ 3. 4.]]
>>> a.transpose()
array([[ 1., 3.],
[ 2., 4.]])
>>> inv(a) # no funciona
array([[-2. , 1. ],
[ 1.5, -0.5]])
>>> u = np.eye(2) # matriz identidad 2x2
>>> u
array([[ 1., 0.],
[ 0., 1.]])
>>> j = np.array([[0.0, -1.0], [1.0, 0.0]])
>>> np.dot (j, j) # matriz producto
array([[-1., 0.],
[ 0., -1.]])
Numpy – operaciones elemento por
elemento - array
>>> a = np.array([1,2,3], float)
>>> b = np.array([5,2,6], float)
>>> a + b
array([6., 4., 9.])
>>> a – b
array([-4., 0., -3.])
>>> a * b
array([5., 4., 18.])
>>> b / a
array([5., 1., 2.])
>>> a % b
array([1., 0., 3.])
>>> b**a
array([5., 4., 216.])
Numpy – operaciones elemento por
elemento - array
>>> a = np.array([[1, 2], [3, 4], [5, 6]], float)
>>> b = np.array([-1, 3], float)
>>> a
array([[ 1., 2.],
[ 3., 4.],
[ 5., 6.]])
>>> b
array([-1., 3.])
>>> a + b
array([[ 0., 5.],
[ 2., 7.],
[ 4., 9.]])
Numpy – array operaciones elemento por
elemento
>>> a = np.array([[1, 2], [3, 4], [5, 6]], float)
>>> b = np.array([-1, 3], float)
>>> a * a
array([[ 1., 4.],
[ 9., 16.],
[ 25., 36.]])
>>> b * b
array([ 1., 9.])
>>> a * b
array([[ -1., 6.],
[ -3., 12.],
[ -5., 18.]])
Numpy – arrays, matrices
Para array de 2 dimensiones NumPy define la clase matriz en
el módulo matrix. Los objects son creados con matrix() o mat()
or convertidos desde un array con el método asmatrix().
>>> m = np.mat([[1,2],[3,4]])
# otra opción
>>> a = np.array([[1,2],[3,4]])
>>> m = np.mat(a)
# otra opción
>>> a = np.array([[1,2],[3,4]])
>>> m = np.asmatrix(a)
m = mat(a) crea una copia del array 'a'. Cambiar valores en ‘a’
no afectará a 'm'.
El método m = asmatrix(a) retorna una nueva referencia al mismo
dato, cambiar valores en 'a' afectará a 'm'.
Numpy – matrices
Las operaciones en array y matrix pueden ser distintas!
>>> a = np.array([[1,2],[3,4]])
>>> m = np.mat(a) # convierte 2-d array a matriz
>>> m
matrix([[1, 2],
[3, 4]])
>>> m = np.matrix([[1, 2], [3, 4]]) # crea matriz m
>>> a[0] # el resultado es 1-dimensional
array([1, 2])
>>> m[0] # el resultado is 2-dimensional
matrix([[1, 2]])
>>> a*a # elemento-por-elemento multiplicación
array([[ 1, 4], [ 9, 16]])
>>> m*m # (algebraica) matriz multiplicación
matrix([[ 7, 10], [15, 22]])
Numpy – matrices
Las operaciones en array y matrix pueden ser distintas!