introducción a pythonpython tiene cinco data types estandar: numbers string list tuples dictionary...
TRANSCRIPT
Introducción a Python
Clase 6
Pablo Cappagli
> python
>>> print ‘Hola mundo!’
Hola mundo!
>>> exit()
>
Python tiene cinco data types estandar:
● Numbers
● String
● List
● Tuples
● Dictionary
>>> var1 = 12
>>> var2 = 12.0
>>> type(var1), type(var2)
<type 'int'> <type 'float'>
Numbers
str = 'Hola Mundo!'
print str
print str[0]
print str[2:5]
print str[2:]
print str * 2
print str + ‘ ’ + ‘Chau’
Strings
Hola Mundo!
H
la
la Mundo!
Hola Mundo!Hola Mundo!
Hola Mundo! Chau
Lists
['abcd', 786, 2.23, 'juan', 70.200000000000003]
abcd
[786, 2.23]
[2.23, 'juan', 70.200000000000003]
[123, 'juan', 123, 'juan']
['abcd', 786, 2.23, 'juan', 70.200000000000003, 123, 'juan']
list = [ 'abcd', 786 , 2.23, 'juan', 70.2 ]
tinylist = [123, 'juan']
print list
print list[0]
print list[1:3]
print list[2:]
print tinylist * 2
print list + tinylist
Tuples
('abcd', 786, 2.23, 'juan', 70.2)
abcd
(786, 2.23)
(2.23, 'juan', 70.2)
(123, 'juan', 123, 'juan')
('abcd', 786, 2.23, 'juan', 70.2, 123, 'juan')
tuple = ( 'abcd', 786 , 2.23, 'juan', 70.2 )
tinytuple = (123, 'juan')
print tuple
print tuple[0]
print tuple[1:3]
print tuple[2:]
print tinytuple * 2
print tuple + tinytuple
Dictionary
‘Este es el primero’
‘Este es el segundo’
{'dept': ‘ventas', 'code': 6734, 'name': 'juan'}
['dept', 'code', 'name']
[‘ventas', 6734, 'juan']
dict = {}
dict[‘uno'] = ‘Este es el primero’
dict[2] = ‘Este es el segundo’
tinydict = {'name': 'juan','code':6734, 'dept': ‘ventas'}
print dict[‘uno']
print dict[2]
print tinydict
print tinydict.keys()
print tinydict.values()
redrum = "-->".join(["Here", "is", "Jhonny!"])
print redrum
fecha = "%d de %s, %d" % (12, ‘noviembre', 1955)
print fecha
nombre = "%(nombre)s %(apellido)s" %{'nombre':'Nicolas', 'apellido':'Chiaraviglio'}
print nombre
Strings
Here-->is-->Jhonny!
12 de noviembre, 1955
Nicolas Chiaraviglio
choice = 'b'
if choice == 'a':
print("You chose 'a'.")
elif choice == 'b':
print("You chose 'b'.")
else:
print("Invalid choice.")
age = 7
if age < 0:
print "This can hardly be true!"
elif age == 1:
print "about 14 human years"
elif age == 2:
print "about 22 human years"
elif age > 2:
human = 22 + (age -2)*5
print "Human years: ", human
Conditionals
for i in [1, 2, 3, 4]:
print i
for x in range(0,10):
print x
for c in "python":
print c
frutas = ['manzana', 'banana', 'pera', 'frutilla']
for fr in frutas:
print fr
else:
print 'no hay mas fruta'
for line in open("a.txt"):
print line
Foor loop
count = 0
while (count < 9):
print 'The count is:', count
count = count + 1
count = 0
while count < 5:
print count, " is less than 5"
count = count + 1
else:
print count, " is not less than 5"
count = 0
while True:
print count, " is less than 5"
count = count + 1
if count >= 5:
print count, " is not less than 5"
break
While loop
def happyBirthdayEmily():
print("Happy Birthday, dear Emily.")
happyBirthdayEmily()
def happyBirthday(person):
print("Happy Birthday, dear " + person + ".")
happyBirthday('Robertito')
def f(x, y):
z = x**2 + x/y
return z
z = f(2.3, 5.1)
print z
Functions
Is an extension to Python, adding support forlarge, multi-dimensional arrays and matrices,along with a large library of high-levelmathematical functions to operate on thesearrays.
Numpy Array
[2, 3, 1, 0], [2, 3, 1, 0]
import numpy as np
x1 = np.array([2, 3, 1, 0])
x2 = np.array((2, 3, 1, 0))
print x1, x2
Numpy Array
[[ 1 2 3 4 5]
[ 6 7 8 9 10]]
int32
(2L, 5L)
10
import numpy as np
z = np.array([[1, 2, 3, 4, 5],[6, 7, 8, 9, 10]])
print z
print z.dtype
print z.shape
print z.size
Numpy Array
[[ 0. 0. 0.]
[ 0. 0. 0.]]
[[0 0 0]
[0 0 0]]
[[1 1 1]
[1 1 1]]
import numpy as np
z = np.zeros([2, 3])
print z
z = np.zeros([2, 3]).astype(np.int32)
print z
z = np.ones([2, 3], dtype=np.int32)
print z
Numpy Array
[ 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13.]
[ 2. 2.1 2.2 2.3 2.4 2.5 2.6 2.7 2.8 2.9]
[ 1. 1.6 2.2 2.8 3.4 4. ]
import numpy as np
z = np.arange(2, 14, dtype=np.float32)
print z
z = np.arange(2, 3, 0.1)
print z
z = np.linspace(1., 4., 6)
print z
Numpy Array
[0 1 2 3 4 5 6 7 8 9]
2 9 9 7
[[0 1 2 3 4]
[5 6 7 8 9]]
8 9
[0 1 2 3 4]
[0 5]
import numpy as np
z = np.arange(10)
print z
print z[2], z[9], z[-1], z[-3]
z.shape = (2,5) # ahora z es 2D
print z
print z[1,3], z[1,-1]
print z[0]
print z[:,0]
Numpy
import numpy as np
y = np.arange(1,36, dtype = np.float64).reshape(5,7)
print y[1:5:2,::3]
z = np.cos(y)
z = np.exp(y)
z = np.round(y)
z = np.abs(y)
w = np.prod(y) #w = np.prod(y, axis=1)
w = np.sum(y)
w = np.cumsum(y)
w = np.mean(y)
w = np.max(y)
Numpy
import numpy as np
N = 10000000
M = 501
my_filter = np.ones(M) astype(np.float16)
my_array = np.random.rand(N).astype(np.float16)
conv_array = np.convolve(my_array, my_filter)
SciPy is an open source Python library used byscientists, analysts, and engineers doing scientificcomputing and technical computing.
SciPy contains modules for optimization linear algebra, integration, interpolation, special functions, FFT, signal and image processing, ODE solvers and other tasks common in science and engineering.
Numpy - Scipy
import numpy as np
from scipy import signal
N = 10000000
M = 501
my_filter = np.ones(M).astype(np.float16)
my_array = np.random.rand(N).astype(np.float16)
conv_array = np.convolve(my_array, my_filter)
convfft_array = signal.fftconvolve(my_array, my_filter)
Numpy - Scipy
import numpy as np
from scipy import signal
import time
N = 10000000
M = 501
my_filter = np.ones(M).astype(np.float16)
my_array = np.random.rand(N).astype(np.float16)
start_time = time.time()
conv_array = np.convolve(my_array, my_filter)
print("--- %s seconds ---" % (time.time() - start_time))
start_time = time.time()
convfft_array = signal.fftconvolve(my_array, my_filter)
print("--- %s seconds ---" % (time.time() - start_time))
--- 36.4789998531 seconds ---
--- 1.4470000267 seconds ---
matplotlibis plotting library forthe Python programming language and its numerical mathematics extension NumPy
Numpy + Matplotlib
import numpy as np
import matplotlib.pyplot as plt
N = 10000
M = 201
my_filter = np.ones(M).astype(np.float16)/M
my_array = np.random.rand(N).astype(np.float16)
conv_array = np.convolve(my_array, my_filter)
plt.figure()
plt.plot(my_array, 'b')
plt.plot(conv_array, 'g')
plt.xlim([0, N])
plt.ylim([-0.5,1.5])
plt.show()
coming soon….