Documentos de Académico
Documentos de Profesional
Documentos de Cultura
Verso Nov/2007 (Python 2.5, NumPy 1.0.4, SciPy 0.6.0, matplotlib 0.90.1, PIL 1.1.6)
C3
Alexandre Gonalves Silva
DCC CCT UDESC
C3
Tpicos
A linguagem Python
Computa
Computao cient
cientfica
C3
Introdu
Introduo
Controles de fluxo
Estruturas de dados
Classes
Mdulos
Exemplos
Exerc
Exerccios
Introdu
Introduo
Mdulos
Aplica
Aplicaes
Exemplos
Exerc
Exerccios
Considera
Consideraes Finais
Referncias
A linguagem
Entidades
Pgina oficial
www.python.org
Comunidade brasileira
C3
www.pythonbrasil.com.br
Usurios e Eventos
Indstria
Cincia
C3
Indstria
Conectiva
Embratel
Blender
Gimp
Inkscape
MayaVi
BitTorrent
WinCVS
Jext
NASA
National Institutes of Health (USA)
National Weather Service (USA)
Lawrence Livermore National Laboratories
Theoretical Physics Division at Los Alamos
National Laboratory
UNICAMP, USP, FURG, INPE, UFES,
UDESC, SOCIESC
Governo
The US Navy
The US Dept. of Agriculture
Bindings/wrapper
PyOpenGL
PyGTK
wxPython
PySDL
PythonMagick
Eventos
PyCon
PyCon UK
PyCon Brasil
EuroPython
pyCologne
SciPy
Caractersticas
Interpretada, de altssimo nvel (very-high-level)
Orientada a objetos
Tratamento de erros e excees
Coleta de lixo automtica
Estruturas de dados avanadas
Com baterias includas (alguns mdulos nativos: os,
cgi, ftplib, gzip, math, re, xmllib, sockets, entre
inmeros outros)
C3
Qualidades
Cdigo aberto e gratuito
Extremamente portvel, bytecode/mquina virtual
Genrica, flexvel e extensvel
Bem projetada
Em crescimento, comunidade ativa (ltima
verso/documentao de Abril/2007)
Pacote interessantes (alguns mdulos instalveis:
administrao de sistemas, interfaces grficas,
internet, banco de dados, programao cientfica,
inteligncia artificial, entre inmeros outros)
C3
Sintaxe
Elegante e simples
Tipagem dinmica (no-declarativa)
Flexibilidade no tratamento de argumentos
Interface simples para estruturas complexas
Rpida prototipao (RAD), ambiente de testes
Blocos marcados pela indentao
Legibilidade
C3
Instalao
No Windows
-
No Linux
-
Outros (Unix-based)
-
Na se
seo _tkinter
_tkinter,, indicar os diret
diretrios das bibliotecas do X11, X11R6 e dos
programas Tcl e Tk.
Tk.
C3
Uso do interpretador
Codificao de caracteres
-
C3
Plataformas e Ambientes
Algumas plataformas
Ol, mundo!
Sada padro - print
C3
Entrada de dados
Entrada de string raw_input
>>> nome = raw_input(
raw_input("Entre com seu nome: ")
")
Entre com seu nome: Alexandre
>>> print nome
Alexandre
>>> type(nome)
type(nome)
<type 'str'>
str'>
C3
Documentao
Comentrios (#)
>>>
>>> # Esta linha um coment
comentrio
C3
Nmeros
Inteiros
Reais
Complexos
2
3
4
5
6
7
C3
>>> 1234
1234
>>> 99999999L
99999999L
>>> (16(16-3*2)/2
5
>>> 7 / 2
3
>>> 7 % 2
1
>>> 077 #octal
63
>>> 0xFF #hexa
255
2
3
4
5
>>> 1.234
1.234
>>> 123.4e123.4e-2
1.234
>>> 7.0 / 2
3.5
>>> 2.0**3
8.0
>>> round(9.6)
10
4
4
Atribuio e Igualdade
Atribuio (=)
>>> valor = 9.5
>>> a, b, c = 10, 20, 30
>>> x = y = 100
C3
>>> x = 5
>>> TESTE
>>> print
True
>>> TESTE
>>> print
False
= x is 5
TESTE
= x is not 5
TESTE
Lgicos e Relacionais
Operadores lgicos
or
and
Operadores relacionais
<
>
<=
>=
Operadores
lgicos bit-a-bit
|
&
Deslocamento
de bits
<<
>>
Exemplos
1
C3
>>> x = 15
>>> TESTE = x < 5 or (x > 10 and x <= 20)
>>> print TESTE
True
>>> TESTE = x < 5 or 10 < x <= 20
>>> print TESTE
True
Built-in (1)
Alguns mtodos:
abs,
abs, apply, bool,
bool, buffer, callable, chr,
chr, classmethod,
classmethod, cmp,
cmp,
coerce, compile, complex,
complex, copyright, credits, delattr,
delattr, dict,
dict,
dir, divmod,
divmod, eval,
eval, execfile,
execfile, exit, file, filter, float,
getattr,
getattr, globals,
globals, hasattr,
hasattr, hash, help, hex, id, input,
input, int,
int,
intern, isinstance,
isinstance, issubclass,
issubclass, iter,
iter, len,
len, license, list,
locals, long, map, max, min, object, oct,
oct, open, ord,
ord, pow,
pow,
property, quit, range, raw_input,
raw_input, reduce, reload, repr,
repr,
round,
round, setattr,
setattr, slice, staticmethod,
staticmethod, str,
str, super, tuple,
tuple, type,
unichr,
unichr, unicode,
unicode, vars,
vars, xrange,
xrange, zip
C3
>>> dir()
dir() # escopo global
['__builtins__
', '__doc__
', '__name__
']
['__builtins__',
'__doc__',
'__name__']
>>> dir(__
builtins__)
) # mostra os mtodos builtins acima
dir(__builtins__
>>> x = 2 + 1j
>>> dir(x)
dir(x) # mostra os mtodos de nmero complexo
Built-in (2)
Ajuda - help()
>>> help(
help(max)
max)
Help on built__:
built-in function max in module __builtin
__builtin__:
max(...)
max(iterable[,
]) -> value
max(iterable[, key=func
key=func])
max(a,
]) -> value
max(a, b, c, ...[, key=func
key=func])
With a single iterable argument, return its largest item.
With two or more arguments, return the largest argument.
C3
Strings
(1)
C3
>>> 'teste...'
teste...'
'teste...'
teste...'
>>> '''"teste
'''"teste '4'..." foi escrito no quadro'''
quadro'''
'"teste
'"teste \'4\
'4\'..." foi escrito no quadro'
quadro'
>>> """Esta
"""Esta string
apresenta mais
de uma linha."""
linha."""
'Esta string\
string\napresenta mais\
mais\nde uma linha.'
linha.'
Strings (2)
Vazia
>>> s1 = ''
Tamanho len()
>>> s2 = 'UDESC'
>>> len(s2)
5
Concatenao (+)
>>> 'DCC/' + s2
'DCC/UDESC'
Replicao (*)
>>> 3*s2
'UDESCUDESCUDESC'
C3
Strings (3)
Slicing - string[inicio:fim:passo]
1
2
3
4
5
6
7
C3
Strings (4)
Transformao em string str(objeto) ou `objeto`
>>> complexo = 2.52.5-1.0j
>>> type(complexo)
type(complexo)
<type 'complex'>
>>> texto = `complexo
`
`complexo`
>>> type(texto)
type(texto)
<type 'str
'>
'str'>
>>> complexo
(2.5(2.5-1j)
>>> texto
'(2.5'(2.5-1j)'
C3
Strings (5)
Exemplo
1
2
3
Alguns mtodos:
capitalize, center,
center, count, decode, encode, endswith,
endswith,
expandtabs,
expandtabs, find,
find, index, isalnum,
isalnum, isalpha,
isalpha, isdigit,
isdigit, islower,
islower,
isspace,
isspace, istitle,
istitle, isupper,
isupper, join, ljust,
ljust, lower, lstrip,
lstrip,
replace, rfind,
rfind, rindex,
rindex, rjust,
rjust, rstrip,
rstrip, split,
split, splitlines,
splitlines,
startswith,
startswith, strip, swapcase,
swapcase, title, translate, upper,
upper, zfill
C3
Listas (1)
Definio, slicing, concatenao e replicao
C3
>>> lista = []
# lista vazia
>>> lista[2:4]
['aa
', 'bb
']
['aa',
'bb']
# slicing
# concatena
concatenao
>>> 3*lista[]
# replica
3*lista[-2:] + ['cc'
['cc']
replicao
['bb
', 8.5, 'bb
', 8.5, 'bb
', 8.5, 'cc
']
['bb',
'bb',
'bb',
'cc']
Listas (2)
Alterao, remoo e insero
1
2
C3
Listas (3)
Sub-listas aninhadas
>>> lista = [30, 40, 8.5]
>>> lista[1] = [100, 200]
>>> lista
[30, [100, 200], 8.5]
>>> lista[1][0]
100
>>> len(lista)
len(lista)
3
Alguns mtodos
append,
append, count,
count, extend,
extend, index,
index, insert,
insert, pop, remove,
reverse,
reverse, sort
C3
Exerccios A
1. Faa um script que entre com um nmero entre 0 e
99999 pelo teclado e produza um string com 5 dgitos
(com zeros a esquerda se for o caso).
2. Considere a definio da seguinte lista de inteiros:
>>> lista = [50, 100, 80, 5, 90, 70, 40, 30, 10, 1, 20]
Primeiro programa
Srie de Fibonacci
>>> a, b = 0, 1
>>> while b < 100:
print b,
a, b = b, a+b
1 1 2 3 5 8 13 21 34 55 89
Consideraes
C3
Controle condicional
Comando if-elif-else
x = input('
input('Entre com um inteiro:
inteiro: ')
')
if x == 0:
print 'Zero'
elif x == 1:
print 'Um'
elif x < 0:
print 'Negativo'
Negativo'
else:
else:
print 'Positivo'
Positivo'
C3
Intervalos range(inicio,fim,passo)
range(2,10,3)
for valor in range(100):
print valor
nomes = ['
['Fulano'
Fulano', 'Ciclano'
Ciclano', 'Beltrano'
Beltrano']
for i in range(len(nomes)):
range(len(nomes)):
print i+1, nomes[i]
nomes[i]
C3
Comando pass
while True:
pass
Outro exemplo
nomes = ['
['Fulano'
Fulano', 'Ciclano'
Ciclano', 'Beltrano'
Beltrano']
for i in nomes:
nomes:
print i
C3
Funes (1)
Comandos def e return
def soma(k1, k2=10):
'''Soma de inteiros no intervalo [k1,k2]'''
soma = 0
valores = []
for i in range(k1, k2+1):
soma = soma + i
valores.append(i)
valores.append(i)
return soma, valores
>>> help(soma)
help(soma)
>>> s1, s2 = soma(3,5)
>>> s1
12
>>> s2
[3, 4, 5]
>>> soma(8)
(27, [8, 9, 10])
C3
Funes (2)
Palavra-chave em parmetros
1
C3
Funes (3)
Funo lambda:
1
def incrementa(n):
return lambda x: x + n
>>> f = incrementa(10)
>>> f(0)
10
>>> f(1)
11
C3
Funes (4)
Ferramentas de programao funcional
- filter
- map
- reduce
1
C3
Funes (5)
Recursividade
def fatorial(n):
fatorial(n):
if n == 0:
return 1
else:
else:
return n * fatorial(nfatorial(n-1)
C3
Erros e Excees
Erros
ZeroDivisionError
NameError
TypeError
>>> 1/0
Traceback (most recent call last):
File "<stdin>", line 1, in ?
ZeroDivisionError: integer division or modulo by zero
Excees
def divisao_segura(a,b):
try:
return a/b
except ZeroDivisionError:
print "Erro: diviso por zero!"
except:
print "Erro inesperado..."
return None
C3
pilha = [1, 2, 3]
pilha.append
(4)
pilha.append(4)
pilha
2, 3, 4]
pilha.pop()
pilha.pop()
pilha
2, 3]
C3
C3
>>> tupla
(12345, 54321, 'oi!')
>>> tupla[0]
tupla[0]
12345
>>> x, y, z = tupla
>>> x
12345
>>> y
54321
>>> z
'oi!'
oi!'
C3
C3
>>> fone
{'aa': 3232, 'cc': 7777, 'bb': 7575}
>>> fone["bb"]
7575
>>> fone.keys()
['aa', 'cc', 'bb']
>>> fone.has_key("cc")
True
Classes (1)
Exemplo
class agenda:
def __init__(self, cont=None):
self.conteudo = cont or []
def adicione(self, nome):
self.conteudo.append(nome)
>>> a = agenda()
>>> a.adicione('Fulano')
>>> a.adicione('Ciclano')
>>> a.conteudo
['Fulano', 'Ciclano']
C3
# construtor
Classes (2)
Sobrecarga de operadores
class racional:
def __init__(self, num, den):
self.num = num
self.den = den
def __str__(self):
return str(self.num) + '/' + str(self.den)
def __mul__(a, b):
c = racional(a.num*b.num, a.den*b.den)
return c
>>>
>>>
>>>
>>>
5
>>>
6
>>>
5/6
C3
a = racional(1,3)
b = racional(5,2)
c = a * b
c.num
c.den
print c
Classes (3)
Herana
class NomeClasseDerivada(NomeClasseBase):
Herana mltipla
class NomeClasseDerivada(Base1, Base2, Base3):
C3
Exerccios B
class racional:
def __init__(self, num, den):
self.num = num
self.den = den
def __str__(self):
return str(self.num) + '/' + str(self.den)
def __mul__(a, b):
c = racional(a.num*b.num, a.den*b.den)
return c
1.
2.
C3
Arquivos
Leitura e escrita
>>> f = open('/
tmp/
/texto.txt'
open('/tmp
texto.txt', 'w')
'w')
Mtodos
>>> f.read
()
f.read()
'Isto o que est
est dentro do arquivo.\
arquivo.\n'
>>> f.readline
()
f.readline()
'Ista a primeira linha do arquivo.\
arquivo.\n
>>> f.readline
()
f.readline()
'Ista a segunda linha do arquivo.\
arquivo.\n'
>>> f.write
('Escrevendo este texto\
f.write(
texto\n')
n')
>>> f.seek
(5)
f.seek(5)
>>> f.read
(1)
f.read(1)
>>> f.close()
C3
Mdulos
Mdulos
2
3
C3
>>>
>>>
>>>
>>>
>>>
a = math.cos(math.pi)
from math import sin, cos, tan
a = cos(math.pi)
from math import *
a = cos(pi)
Execuo de mdulos
Modos de execuo de um script em arquivo:
$ python nome.py
run script (F5) no IDLE
execute buffer (Ctrl+c Ctrl+c) no emacs
Script executvel no Unix:
#! /usr/bin/env python
Organizao em mdulos:
C3
Alguns Mdulos
Alguns mdulos inclusos:
math
time
string
sys
os
cgi
Tkinter
C3
pygame
PyOpenGL
PIL
NumPy
Mdulo time
Exemplo:
from time import time
t0 = time()
#...
#Colocar o trecho de cdigo aqui
#...
t = time() - t0
print 't = %.4f \n' %t
C3
Mdulo string
Exemplo:
C3
>>> exec(comando)
Mdulo sys
Exemplo:
1
2
C3
Mdulo cgi
#!/bin/python
# Calendrio dinmico
print 'Content-type: text/html\n'
print '<HTML><TITLE>Calendrio Dinmico</TITLE>'
print '<BODY>'
try:
import cgi
from time import time, localtime
# calendar
ano, mes, dia = localtime(time())[:3]
print '<H1>Joinville, %02d/%02d/%04d</H1>' %(dia, mes, ano)
print '...'
opcao = cgi.FieldStorage()
...
except:
print '<HR><H3>Erro no CGI!</H3><PRE>'
print '</BODY></HTML>'
C3
import Tkinter
from Tkconstants import *
tk = Tkinter.Tk()
frame = Tkinter.Frame(tk, relief=RIDGE, borderwidth=2)
frame.pack(fill=BOTH, expand=1)
label = Tkinter.Label(frame, text="Ol, mundo!")
label.pack(fill=X, expand=1)
button = Tkinter.Button(frame, text="Sada",
command=tk.destroy)
button.pack(side=BOTTOM)
tk.mainloop()
C3
C3
Exerccios C
Crie dois arquivos texto A e B com N nmeros
aleatrios inteiros. Ex. de nmero entre [0,1000):
>>> import random
>>> a = random.randint(0,1000)
C3
Computao cientfica
C3
Introduo
(1)
C3
Introduo
Alguns domnios
C3
Simulao numrica
Predies
Anlise de dados
Visualizao cientfica
Reconhecimento de padres
Processamento grfico
Inteligncia artificial
Redes
Pesquisa operacional
Contabilidade, economia
(2)
Introduo
(3)
Linguagens usuais
FORTRAN
C
Linguagens facilitadoras
C3
MATLAB
GNU Octave
SciLab
Mathematica
Python
+
Mdulos auxiliares
Pacote numrico
C3
www.numpy.org
Computao cientfica
Array multidimensional
Histrico
Mdulos
Numeric
numarray
numpy
Principal
An
Anlise de Fourier
lgebra Linear
Lista de funes
(1)
C3
Lista de funes
(2)
C3
Lista de mtodos
Criao de array, tipos e mtodos
1
>>> type(a)
<type 'numpy.ndarray'>
>>> a.dtype
dtype('int32')
C3
>>> b = a.astype('float')
>>> b
array([ 1., 2., 3.])
(1)
Lista de mtodos
(2)
C3
Criao de arrays
Criao de array
1
2
3
4
Dimenso de um array
>>> lista = numpy.array([[1,2,3],[4,5,6]])
>>> lista.shape
(2, 3)
C3
Arrays no numpy
1D x 2D
1
2
3
4
>>> a = numpy.arange(0.0,1.0,0.1)
# a.T nao se altera
>>> print a
[ 0.
0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9]
>>> a.shape
(10,)
>>> b = a[numpy.newaxis,:]
>>> b.shape
(1, 10)
>>> c = a[:,numpy.newaxis]
>>> c.shape
(10, 1)
Funes matemticas
5
>>> y = numpy.sin(a)
>>> print y
[ 0.
0.56464247
C3
0.09983342
0.64421769
0.19866933
0.71735609
0.29552021 0.38941834
0.78332691]
0.47942554
Algumas operaes
Transposio
1
C3
>>> a = numpy.array([[1,3],[-2,0]])
>>> b = 2 * a
>>> c = a * b
>>> numpy.dot(a, b)
array([[-10,
6],
[ -4, -12]])
Processamentos simples
Criao, valores diferentes de zeros, limiarizaes
C3
>>> a = numpy.array([[1,0,0],[0,5,6],[7,0,0],[0,11,0]])
>>> print a
[[ 1 0 0]
[ 0 5 6]
[ 7 0 0]
[ 0 11 0]]
>>> a.nonzero
# ou numpy.nozero(a)
(array([0, 1, 1, 2, 3]), array([0, 1, 2, 0, 1]))
>>> b = a > 5
>>> print b
[[False False False]
[False False True]
[ True False False]
[False True False]]
Seleo de submatriz
Nome_da_Matriz[incio:fim:passo]
C3
>>> a = numpy.array([0,1,2,3,4])
>>> a[1:3]
# da posio 1 at a posio 3 (exclusive)
array([1, 2])
>>> a[-1]
4
>>> a[3:]
# ou a[3::]; posio at o ltimo termo
array([3, 4])
# ltimo termo
Varredura implcita
Grade de ndices
>>>
>>>
[[0
[1
>>>
[[0
[0
>>>
[[0
[1
x,y =
print
0 0 0
1 1 1
print
1 2 3
1 2 3
print
1 2 3
2 3 4
numpy.indices((2, 5))
x
0]
1]]
y
4]
4]]
x + y
4]
5]]
Chamada de funo
>>> def funcao(x,y):
return x+y
>>> z = numpy.fromfunction(funcao, (2,5))
>>> print z.astype('int')
[[0 1 2 3 4]
[1 2 3 4 5]]
C3
Exerccios
Matriz em forma de moldura
>>>
>>>
>>>
>>>
import numpy
a = numpy.ones((11, 11))
b = numpy.zeros((5, 5))
a[3:8,3:8] = b
C3
Python x MATLAB
Sintaxe Python/numpy
Python/numpy
Sintaxe MATLAB
C3
IMG
Outros mdulos
pylab
from pylab import *
>>> x = arange(0,5*pi,0.1)
>>> y = cos(x)
>>> plot(y)
Gnuplot
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>
C3
(1)
Outros mdulos
ipython + TVTK
>>> from enthought.tvtk.tools import mlab
>>> from scipy import *
>>> def f(x,y):
return sin(x+y) + sin(2*x-y) + cos(3*x+4*y)
>>> x = linspace(-5.0, 5.0, 200)
>>> y = linspace(-5.0, 5.0, 200)
>>> fig = mlab.figure()
>>> surf = mlab.SurfRegularC(x,y,f)
>>> fig.add(surf)
C3
(2)
Documentao
C3
Caractersticas
C3
No compilao ou ligao
No declarao de tipos
Gerenciamento automtico de memria
Tipos de dados e operaes de alto nvel
Programao orientada a objetos
Extending e embedding em C
Classe, mdulos e excees
Carregamento dinmico de mdulo em C
Interativo, de natureza dinmica
Acesso a informaes do interpretador
Grande portabilidade, compilao para byte-code
Referncias
Livros
Flvio Coelho. Computao Cientfica com Python. 1a Edio do autor, 2007.
Mark Pilgrim.
Pilgrim. Mergulhando no Python.
Python. Alta Books,
Books, 1a Edi
Edio, 2005.
Documentao eletrnica
http://www.python.org/doc
http://www.pythonbrasil.com.br
Pacotes
http://www.numpy.org
http://www.scipy.org
Alguns trabalhos
http://www.dca.fee.unicamp.br/ia636
http://www.mmorph.com/pymorph
http://ortoprog.sourceforge.net
C3
C3
C3
Numeric/ufuncobject.h
ufuncobject.h
static PyObject *ErrorObject;
ErrorObject;
static PyObject *
xx_somar_diagonal
(PyObject *self,
xx_somar_diagonal(
self, PyObject *args)
args) {
PyObject *input;
PyArrayObject *array;
array;
double sum;
sum; int i, n;
if (!PyArg_ParseTuple
(args,
", &input)) return NULL;
(!PyArg_ParseTuple(
args, "O:somar_diagonal
"O:somar_diagonal",
array = (PyArrayObject
(PyArrayObject *) PyArray_ContiguousFromObject(input,
PyArray_ContiguousFromObject(input, PyArray_DOUBLE,
PyArray_DOUBLE, 2, 2);
C3
/* Inicializa
Inicializao do Numeric */
d = PyModule_GetDict(m);
PyModule_GetDict(m);
ErrorObject = PyErr_NewException("
xx.
.error",
PyErr_NewException("xx
error", NULL, NULL);
PyDict_SetItemString(d,
", ErrorObject);
PyDict_SetItemString(d, "error
"error",
ErrorObject);
}
C3
Anexo - Desempenho
Quadrado
Iterao
16
14
Python
MATLAB
0,12
Python
MATLAB
0,10
12
10
8
6
4
0,08
0,02
0,06
0,04
0,00
50x50
100x100
256x256
512x512
50x50
100x100
Multiplicao de Matrizes
5,00
Python
256x256
512x512
256x256
512x512
FFT
MATLAB
0,60
Python
MATLAB
0,50
4,00
0,40
3,00
0,30
2,00
0,20
1,00
0,10
0,00
0,00
50x50
C3
100x100
256x256
512x512
50x50
100x100