Python Curso
Python Curso
J o v e n t i n o de O l i v e i r a Campos
jo v e ntino o @g ma il. co m
3 0 de Maio de 2 0 1 5
Contedo
Parte I
I nt r oduo
Sintaxe
Tipos de dados
Construes bsicas ( i f , w h i l e , f o r , . . . )
L i s t a s , Tuplas
Funes
Parte I I
Dicionrio
Orientao a objetos
Programao f u n c i onal
Mdulos
Arquivos
Parte I I I
Computao c i e n t f i c a com Python
Parte I V
B i b l i o t e c a s e programas i n t e r ess ant es
2 / 180
Parte I
I ntr odu o linguagem Python
3 / 180
Sobre a linguagem Python
C r i a da por Guido van
Rossum em 1991
Linguagem de Al t o N v e l
Interpretada
Programao:
Modular
Orientada a objetos
Funcional
Tipagem dinmica e f o r t e
Vasta coleo de
bibliotecas
Cdigo a b e r t o (GPL)
4 / 180
Sobre a linguagem Python
D i ve r s a s e s t r u t u r a s de dados n a t i v a s
l i s t a , t u p l a , dicionrio
Gerenciamento de memria automtico
Tratamento de excees
Sobrecarga de operadores Indentao
para e s t r u t u r a de bloco
Multiplataforma
Bem documentada
M uito usada
5 / 180
Sobre a linguagem Python
D i ve r s a s e s t r u t u r a s de dados n a t i v a s
l i s t a , t u p l a , dicionrio
Gerenciamento de memria automtico
Tratamento de excees
Sobrecarga de operadores Indentao
para e s t r u t u r a de bloco
Multiplataforma
Bem documentada
M uito usada
Quem usa?
Blender, GIMP, Inkscape, YouTube, NASA, CERN
SPSS, ESRI, ArcGIS, Abaqus, OpenOffice Google,
YouTube, B a t t l e f i e l d 2
6 / 180
Porque usar Python?
F c i l , simples
S i n t a x e limpa
Di ve r s a s b i b l i o t e c a s j i n c l u s a s
Mais e x pr e s s i va do que muitas linguagens ( C / C + + ,
P e r l , Java)
Interativa
P r o t t i p o s r pi dos
Al t a produtividade
I n t e r f a c e s para o u t r a s linguagens como C/C++ e
Fortran
7 / 180
Vamos comear
8 / 180
Vamos comear
>>>
>>> p r i n t 2 + 2
4
>>> p r i n t p i n k + f l o y d
p i n k f l o yd
>>> x = 2 * * 3
9 / 180
Alguns detalhes
No p r e c i s o t e r m i n a r comandos com ;
No p r e c i s o d e c l a r a r o t i p o de dado das
variveis
>>> a = 2 * * 3
>>> a
8
>>> x = 2 . 9 + 6 . 5 + 1 . 1
>>> x
10.5
>>> p r i n t t yp e ( a )
<type i n t >
>>> p r i n t t yp e ( x )
<type f l o a t >
10 / 180
Alguns detalhes
No p r e c i s o t e r m i n a r comandos com ;
No p r e c i s o d e c l a r a r o t i p o de dado das
variveis
>>> a = 2 * * 3
>>> a
8
>>> x = 2 . 9 + 6 . 5 + 1 . 1
>>> x
10.5
>>> p r i n t t yp e ( a )
<type i n t >
>>> p r i n t t yp e ( x )
<type f l o a t >
11 / 180
Tipos de Dados
>>> x = 2 * * 3
>>> x / 2
4
>>> t yp e ( x )
int
>>> x = 1 0 . 5 Tipos de dados bsicos
>>> t yp e ( x ) i n t , long, f l o a t ,
float
complex
>>> m = ( 6 . 8 + 9 . 4 + 8 . 4 ) / 3
>>> m bool
8.200000000000001 Ot i p o de uma v a r i v e l
>>> m > 6 . 0
True muda conforme o v a l o r
>>> (m >= 9 . 0 ) and (m <= 1 0 . 0 ) atribudo
False
>>> c1 = 3 + 1 j
>>> c2 = c o m p l e x ( - 3 , 2 )
>>> c1 + c2
3j
12 / 180
Tipagem f o r t e
>>> p r i n t c + q
Traceback (most r ecent c a l l l a s t ) :
F i l e " < s t d i n > " , l i n e 1 , i n <module>
TypeEr r or: cannot concatenate s t r and i n t objects
13 / 180
Tipagem f o r t e
>>> p r i n t c + q
Traceback (most r ecent c a l l l a s t ) :
F i l e " < s t d i n > " , l i n e 1 , i n <module>
TypeEr r or: cannot concatenate s t r and i n t objects
14 / 180
St r i ngs
15 / 180
St r i ngs
>>> s i m p l e s
simples
>>> "dupla"
dupla
16 / 180
St r i ngs
Como e v i t a r a quebra de l i n h a ?
17 / 180
St r i ngs
Como e v i t a r a quebra de l i n h a ?
>>> p r i n t ( C : \ d i r e t o r i o \ \ n o v o \ \ n a d a . e x e )
18 / 180
St r i ngs
Como e v i t a r a quebra de l i n h a ?
>>> p r i n t ( C : \ d i r e t o r i o \ \ n o v o \ \ n a d a . e x e )
Modos e s p e c i a i s de s t r i n g s :
raw s t r i n g
unicode s t r i n g
>>> p r i n t ( r C : \ d i r e t o r i o \ n o v o \ n a d a . e x e )
C:\diretorio\novo\nada.exe
>>> p r i n t ( u " \ u 2 1 9 2 " )
19 / 180
St r i ngs
S t r i n g s so i mut ve i s
>>> " h e l l o " + "world" # concatenacao
helloworld
>>> s = h e l l o
>>> s [ 0 ] = j
Traceback (most r ecent c a l l l a s t ) :
F i l e " < s t d i n > " , l i n e 1 , i n <module>
TypeEr r or: s t r o b j e c t does not support item assignment
>>> sn = j + s [ 1 : ]
>>> sn
j el l o
20 / 180
St r i ngs
>>> t e x t = o va l o r de p i eh = + str(pi)
21 / 180
St r i ngs
>>> t e x t = o va l o r de p i eh = + str(pi)
Formatadores e s p e c i a i s
>>> t e x t = o va l o r de p i eh = %f % p i
>>> p r i n t t e x t
>>> a = 10.2
>>> i = 100
>>> s = oi
>>> t e x t = "float=%f inteiro= % d string=%s" % ( a , i , s )
22 / 180
St r i ngs
Acesso s e q u e n c i a l , em f a t i a s ou d i r e t o ( n d i c e )
Slice: s[start:end]
23 / 180
Strings - Mtodos
l o w e r , upper, c a p i t a l i z e
s p l i t , strip, join
f i n d , replace
startsw ith, islower, . . .
24 / 180
Strings - Mtodos
l o w e r , upper, c a p i t a l i z e
s p l i t , strip, join
f i n d , replace
startsw ith, islower, . . .
>>> " . ".join("PYTHON I S P OW E R FU L" .lower ().split( ) ) + " ! ! ! "
p yt h o n . i s . p o w e r f u l ! ! ! s
25 / 180
Strings - Mtodos
l o w e r , upper, c a p i t a l i z e
s p l i t , strip, join
f i n d , replace
startsw ith, islower, . . .
>>> " . ".join("PYTHON I S P OW E R FU L" .lower ().split( ) ) + " ! ! ! "
p yt h o n . i s . p o w e r f u l ! ! ! s
Passo a passo
>>> s = "PYTHON I S POWERFUL"
>>> s . l o w e r ( )
python i s p o w e r f u l
>>> s . l o w e r ( ) . s p l i t ( )
[python , i s , powerful]
>>> a = s . l o w e r ( ) . s p l i t ( )
>>> " . " . j o i n ( a )
p yt h o n . i s . p o w e r f u l
>>> " . " . j o i n ( a ) + " ! ! ! "
p yt h o n . i s . p o w e r f u l ! ! !
26 / 180
Strings - Mtodos
# split()
>>> s = monty python and the f l y i n g c i r c u s
>>> p r i n t s . s p l i t ( )
[ m o n t y , p yt h o n , a n d , t h e , f l y i n g , c i r c u s ] # opa, uma lista!
# count()
>>> p r i n t s . c o u n t ( " t h " )
# join()
>>> s = "em busca do c a l i c e sagrado"
>>> s2 = s . s p l i t ( )
>>> p r i n t " / " . j o i n ( s 2 )
em/busca/do/calice/sagrado
Ainda p o s s v e l r e a l i z a r d i v e r s a s o u t r a s
operaes com s t r i n g s
27 / 180
L i s t a s e Tuplas
E s t r u t u r a s de dados n a t i v a s : l i s t , tuple
Colees de o b j e t o s heterogneos
Crescem a t o l i m i t e da memria
Acesso s e q u e n c i a l , em f a t i a s ou d i r e t o
Mtodos para a d i c i o n a r , remover, o r d e n a r ,
procurar, contar
L i s t a s so mutveis e t u p l a s so i mut ve i s
Tuplas no podem ser a l t e r a d a s depois de criadas
L i s t a s so d e l i m i t a d a s por [ e ]
Tuplas so d e l i m i t a d a s por ( e )
28 / 180
Tupl as
>>> t _ va z i a = ( )
>>> p r i n t l e n ( t _ v a z i a )
0
>>> u _ tupla = ( o i , )
>>> p r i n t l e n ( u _ t u p l a )
1
29 / 180
Tupl as
>>> x , y , z = t # desempacotar t u p l a
>>> p r i n t y
54321
30 / 180
Li st as
"Ar r a ys f l e x v e i s "
>>> a = [ s p a m , e g g s , 1 0 0 , 1234]
>>> a
[ s p a m , e g g s , 1 0 0 , 1234]
>>> a [ 0 ]
spam
>>> a [ 3 ]
1234
>>> a [ - 2 ]
100
>>> a [ 1 : - 1 ]
[ e g g s , 100]
>>> a [ : 2 ] + [ b a c o n , 2 * 2 ]
[spam, eggs, bacon, 4]
>>> 3 * a [ : 3 ] + [ B o o ! ]
[spam, e g g s , 100, spam, e g g s , 100, spam, e g g s , 100, B o o ! ]
31 / 180
Lista - Mtodos
>>> a = range(5)
>>> print a Sa da
>>> a.append(5)
>>> print a [ 0 , 1, 2, 3, 4]
>>> a.insert(0,42) [ 0 , 1, 2, 3, 4, 5]
>>> print a [42, 0, 1, 2, 3, 4, 5]
>>> a.reverse() [ 5 , 4 , 3 , 2 , 1 , 0 , 42]
>>> print a [ 0 , 1 , 2 , 3 , 4 , 5 , 42]
>>> a.sort()
>>> print a
Outros mtodos
e x t e n d ( L ) : append de uma l i s t a L
remove(x): remove p r i m ei ra ocorrncia de x
i n d e x ( x ) : retorna o n d i c e da p r i m e ir a
ocorrncia de x na lista
count(x): retorna o nmero de ocorrncias de x
na l i s t a
32 / 180
Lista
Representao
33 / 180
Lista
Representao
Al t er aes
34 / 180
Li st a
Concat enao
>>> o r i g i n a l = [ H , H e , L i ]
>>> temp = [ B e ]
>>> f i n a l = o r i g i n a l + temp
>>> p r i n t f i n a l
[ H , He, L i , Be]
35 / 180
Li st a
Sl i ce
>>> l = r ange (10 )
>>> l [ 2 : 6 ]
[ 2 , 3, 4, 5]
36 / 180
Li st a
Sl i ce
>>> l = r ange (10 )
>>> l [ 2 : 6 ]
[ 2 , 3, 4, 5]
L i s t a aninhada
37 / 180
Li st a
Sl i ce
>>> l = r ange (10 )
>>> l [ 2 : 6 ]
[ 2 , 3, 4, 5]
L i s t a aninhada
>>> l a = [ [ a , b ] , [ 1 , 2 ] , [ 3 , 4 ] ]
>>> p r i n t l a
[[a , b], [1, 2], [3, 4]]
>>> p r i n t l a [ 0 ]
[a, b]
>>> p r i n t l a [ 1 ]
[ 1 , 2]
>>> p r i n t l a [ 2 ] [ 1 ]
4
38 / 180
Built-ins
39 / 180
Built-ins
Alguns exemplos
range para l i s t a s
a l l e any para a p l i c a r f i l t r o s booleanos em
listas
d i c t , l i s t , set e object
sorted e reversed para ordenar l i s t a s
i n t , s t r e f l o a t que servem para c o n s t r u i r t i p o s
min, max e sum para operaes matemticas em l i s t a s
help, d i r
40 / 180
Built-ins
Documentao
ht t p: / / docs. pyt hon. or g/ l i br ar y/ f unct i ons. ht ml
http://docs.python.org/
41 / 180
A funo range
>>> h e l p ( r a n g e )
42 / 180
A funo range
>>> h e l p ( r a n g e )
range(...)
r ange([star t , ] stop[, step]) -> l i s t of integers
43 / 180
A funo range
>>> h e l p ( r a n g e )
range(...)
r ange([star t , ] stop[, step]) -> l i s t of integers
44 / 180
bool
>>> y = True
>>> not y
False
45 / 180
I ndent ao
i f (num % 2 == 0 )
{
i f (num % 2 == 0 ) {
par = par + 1 ;
par = par + 1 ;
pr i nt f ( " Par " ) ;
printf("Par");
}
} else {
else
impar = impar + 1 ;
{
printf("Impar");
impar = impar + 1 ;
}
printf("Impar");
}
46 / 180
I ndent ao
i f (num % 2 == 0 )
{
i f (num % 2 == 0 ) {
par = par + 1 ;
par = par + 1 ;
pr i nt f ( " Par " ) ;
printf("Par");
}
} else {
else
impar = impar + 1 ;
{
printf("Impar");
impar = impar + 1 ;
}
printf("Impar");
}
Em Python a e s t r u t u r a de bloco d e f i n i d a p e l a
indentao do c di go!
47 / 180
I ndent ao
I s s o mesmo!
Tudo que pe r te nc e a ummesmo bloco f i c a a l i nha do no
mesmo n v e l do cdigo f o n t e .
i f num % 2 == 0 :
par = par + 1
print Par
else:
impar = impar + 1
print Impar
48 / 180
I ndent ao
I s s o mesmo!
Tudo que pe r te nc e a ummesmo bloco f i c a a l i nha do no
mesmo n v e l do cdigo f o n t e .
i f num % 2 == 0 :
par = par + 1
print Par
else:
impar = impar + 1
print Impar
E r r o de indentao
i f x % 2 == 0 :
print par
F i l e "<stdin>" , l i n e 2
print par
^
I n d e n t a t i o n E r r o r : expected an indented block
I f - El se
i f exp:
comandos
else:
comandos
If-Else-If-Else
i f exp:
comandos
e l i f exp:
comandos
else:
comandos
50 / 180
Est r ut ur as de Controle
If-elif-else
I f - El se Exempl o
>>> x = int(r aw _ input (" N um er o: " ) )
i f exp:
>>> i f x < 0:
comandos
... p r i n t Negativo
else:
... e l i f x == 0 :
comandos
... print Zero
... else:
... print Positivo
51 / 180
Estrutur a s de Controle
F o r , W hile
For Whi l e
l s t = [10,20,30,oi,tchau] while exp:
f o r item i n l s t : comandos
p r i n t item
while exp:
f o r l e t r a i n "python" : i f exp2:
print letr a comandos1
i f exp3:
f o r k i n range(100): break
print k comandos2
52 / 180
Estrutur a s de Controle
F o r , W hile
For Whi l e
l s t = [10,20,30,oi,tchau] while exp:
f o r item i n l s t : comandos
p r i n t item
while exp:
f o r l e t r a i n "python" : i f exp2:
print letr a comandos1
i f exp3:
f o r k i n range(100): break
print k comandos2
>>> a = [ c a t , s p i d e r , wor m ]
>>> f o r x i n a :
... print x, len(x)
...
cat 3
spi der 6
worm 4
53 / 180
Estrutur a s de Controle
F o r , W hile
For Whi l e
l s t = [10,20,30,oi,tchau] while exp:
f o r item i n l s t : comandos
p r i n t item
while exp:
f o r l e t r a i n "python" : i f exp2:
print letr a comandos1
i f exp3:
f o r k i n range(100): break
print k comandos2
>>> a = [ c a t , s p i d e r , wor m ]
>>> f o r i i n r a n g e ( l e n ( a ) ) :
>>> f o r x i n a :
... print i , a [ i ]
... print x, len(x)
...
...
1 cat
cat 3
2 spider
spi der 6
3 worm
worm 4
54 / 180
Outras construes para loops
enumerate()
>>> nomes = [ A n a , M a r i a , C a r l a ]
>>> f o r par i n enumerate(nomes):
... p r i n t par
(0, Ana)
(1, Maria)
(2, Clara)
55 / 180
Outras construes para loops
zip()
>>> nomes = [ P a t o , G a n s o , H u l k ]
>>> gols = [ 2 , 0 , 8 ]
>>> f o r n , g i n z ip(nom es , go l s ):
... p r i n t %s f e z %d g o l s % ( n , g )
...
Pato f e z 2 gols
Ganso f e z 0 gols
Hulk f e z 8 gols
56 / 180
Estrutur a s de Controle
Switch
>>> i f n == 0 :
... p r i n t Voce digitou z e r o .
... e l i f n == 1 :
... p r i n t Voce d i g i t o u um.
... e l i f n == 2 :
... p r i n t Voce digitou d o i s .
... e l i f n == 3 :
... p r i n t Voce digitou t r e s .
... else:
... p r i n t Voce d i g i t o u qualquer c o i s a .
57 / 180
Funes
Procedimento
def nome(arg1, a r g 2 , . . . ) :
comandos
return
Funo
def nome1(arg1, a r g 2 , . . . ) :
comandos
r e t u r n expressao
def nome2(arg1, a r g 2 , . . . ) :
comandos
r e t u r n exp1, exp2, exp3
def nome3(arg1, a r g 2 , a r g x = va l o r ) :
comando
r e t u r n exp
58 / 180
Funes
Procedimento
def nome(arg1, a r g 2 , . . . ) :
comandos
return >>> def p a r ( n ) :
... r e t u r n ( n % 2 == 0 )
59 / 180
Funes
>>> a , b = m u l t ( 2 )
>>> p r i n t a , b # 2 4
>>> a , b = m u l t ( 2 , num=10)
>>> p r i n t a , b # 2 20
>>> a , b = m u l t ( 3 , 5 )
>>> p r i n t a , b # 3 15
60 / 180
Funes
Exempl o
def d i v i d e ( a , b ) :
"""
D ivide operando a e b usando d i v i s a o i n t e i r a . Returna o
quociente e r e s t o da d i v i s a o em uma t u p l a . " " "
q = a // b
r = a - q * b
return q , r
Uso
>>> d i v ( 1 0 , 2 )
( 5 , 0)
>>> mq, mr = d i v ( 1 0 , 3 )
>>> p r i n t mq, mr
3 1
>>> h e l p ( d i v i d e )
divide(a, b)
D i vi d e operando a e b usando d i vi s a o i n t e i r a . Returna
o quociente e r e s t o da d i vi s a o em uma t u p l a .
61 / 180
EXERC CI O
Dicas:
st r i ng
split
slice
acesso sequencial
C r i e uma r qui vo t e x t o para c o d i f i c a r a sua
funo.
V e j a o exemplo a s e g u i r .
62 / 180
EXERC CI O
def u r l _ p a r s e ( u r l ) :
"""
Implemente a funcao abaixo
"""
pass
u r l t e s t e = raw_input()
print url_parse(urlteste)
63 / 180
EXERC CI O
Uma p o s s v e l soluo
def u r l _ p a r s e ( u r l ) :
"""
Essa funcao recebe uma URL v a l i d a e r e t o r n a a s t r i n g contendo o
nome da pagina p r i n c i p a l .
Por exemplo:
ur l _ par se( http:// sem com p .icm c .usp .br / pr ogr am acao )
retorna
semcomp.icmc.usp.br
"""
proto, resto = u r l . s p l i t ( : )
resto = r e s t o[ 2 : ]
temp = r e s t o . s p l i t ( / )
host = temp[0]
r e t u r n host
64 / 180
EXERC CI O
Mdulo
Vamos supor que voc tenha c o d i f i c a d o a funo
u r l _ p a r s e ( ) em um a r qui vo f o n t e chamado t e s t e . p y
Como posso usar essa funo em outr os programas?
65 / 180
EXERC CI O
Mdulo
Vamos supor que voc tenha c o d i f i c a d o a funo
u r l _ p a r s e ( ) em um a r qui vo f o n t e chamado t e s t e . p y
Como posso usar essa funo em outr os programas?
Basta usar os comandos from e i mpor t da s e gui nte
forma
>>> from t e s t e import ur l _ par se
>>> p r i n t url _ parse( "ht tp: //sem com p.icm c.usp.br /pr ogr am acao " )
semcomp.icmc.usp.br
66 / 180
Parte I I
Uma i ntr odu o um pouco mais avanada
67 / 180
Di ci onr i o
68 / 180
Di ci onr i o
69 / 180
Di ci onr i o
>>> d = { }
>>> d [ p a u l o ] = 25
>>> d [ j o s e ] = 16
>>> d [ a l i c e ] = 21
>>> p r i n t d
{ paulo : 25, j o s e : 16, a l i c e : 21}
>>> p r i n t d [ a l i c e ]
21
>>> d [ a l i c e ] = P a r i s
>>> p r i n t d
{ paulo : 25, j o s e : 16, a l i c e : Paris}
>>> j o s e i n d
True
>>> c = { J u i z de F o r a : 2 5 . 0 , O x f o r d : r a i n , R i o de J a n e i r o : 40.0}
>>> p r i n t c [ P e t r o p o l i s ] # KeyError
>>> i f P e t r o p o l i s i n c : p r i n t c [ P e t r o p o l i s ] # e v i t a KeyError
>>> p r i n t c . g e t ( S a n D i e g o ) # r e t o r n a None
None
70 / 180
Di ci onr i o
Percorrendo d i c i o n r i o s
>>> f o r key i n d :
... p r i n t key
>>> p r i n t d . k e ys ( )
[a, c, b]
>>> p r i n t d . v a l u e s ( )
[ 1 0 , 30, 20]
>>> f o r k , v i n d . i t e m s ( ) : p r i n t k , - > , v
71 / 180
L i s t comprehension
72 / 180
L i s t comprehension
>>> nova = [ x * x f o r x i n l i s t a ]
>>> p r i n t nova
[ 4 , 16, 36, 64]
73 / 180
L i s t comprehension
74 / 180
L i s t comprehension
75 / 180
L i s t comprehension
Outro exemplo
>>> t e x t o = "There i s someone i n my head but i t i s not m e " . s p l i t ( )
>>> nova = [ ( p . u p p e r ( ) , p . l o w e r ( ) , l e n ( p ) ) f o r p i n texto]
>>> p r i n t nova
[(THERE, t h e r e , 5 ) ,
(IS, is, 2),
(SOMEONE, someone, 7 ) ,
...
]
76 / 180
L i s t comprehension
Outro exemplo
>>> t e x t o = "There i s someone i n my head but i t i s not m e " . s p l i t ( )
>>> nova = [ ( p . u p p e r ( ) , p . l o w e r ( ) , l e n ( p ) ) f o r p i n texto]
>>> p r i n t nova
[(THERE, t h e r e , 5 ) ,
(IS, is, 2),
(SOMEONE, someone, 7 ) ,
...
]
77 / 180
Cl asses
>>> p = P onto()
>>> p r i n t p
< main .Ponto instance a t 0x7f891f392098>
78 / 180
Cl asses
>>> p = P onto()
>>> p r i n t p
< main .Ponto instance a t 0x7f891f392098>
Const r ut or
class Ponto:
def i n i t ( s e l f , x , y ) :
self .xC o or d = x
self . yC o or d = y
p = Ponto(2.0, 1 . 0 )
79 / 180
Cl asses
s e l f umparmetro e s p e c i a l que p r e c i s a s e r
i n c l u d o na d e f i n i o de cada mtodo e p r e c i s a
s e r o p r i m e i r o pa r me tr o.
Quando ummtodo i nvoc a do, esse parmetro
automaticamente preenchido com a r e f e r n c i a ao
o b j e t o no qua l o mtodo f o i i nvoc a do.
80 / 180
Cl asses
s e l f umparmetro e s p e c i a l que p r e c i s a s e r
i n c l u d o na d e f i n i o de cada mtodo e p r e c i s a
s e r o p r i m e i r o pa r me tr o.
Quando ummtodo i nvoc a do, esse parmetro
automaticamente preenchido com a r e f e r n c i a ao
o b j e t o no qua l o mtodo f o i i nvoc a do.
class Ponto:
def i n i t ( s e l f , x , y ) :
self .xC o or d = x
self . yC o or d = y
def g e t X ( s e l f ) :
r e t u r n self .xC o or d
def g e t Y ( s e l f ) :
r e t u r n self . yC o or d
p = Ponto(3.0, 1 . 5 )
print p.getX () , p.getY()
81 / 180
Cl asses
82 / 180
Cl asses
Calcular a distncia
class Ponto:
# ...
def d i s t a n c i a ( s e l f , p t ) :
dx = self .xC oo r d - pt.xCoord
dy = self . yC o or d - pt.yCoord
return math.sqrt(dx ** 2 + d y* * 2 )
83 / 180
Cl asses
Calcular a distncia
class Ponto:
# ...
def d i s t a n c i a ( s e l f , p t ) :
dx = self .xC oo r d - pt.xCoord
dy = self . yC o or d - pt.yCoord
return math.sqrt(dx ** 2 + d y* * 2 )
p1 = P o n t o ( 0 , 0 ) ; p2 = P o n t o ( 1 . 0 , 1 . 0 )
p2.shift(1.0, 1.0)
p r i n t "Distancia = " , p2.distancia(p1)
84 / 180
Classes
Usando mdulos
# Arquivo ponto.py
import math
class P oint :
def i n i t ( s e l f , x , y ) :
self .xC o or d = x
self . yC o or d = y
def getX ( s e l f ) :
r e t u r n self .xC o or d
def getY( s e l f ) :
r e t u r n self . yC o or d
def s h i f t ( s e l f , x I n c , yInc ) :
self . _ xC oor d += xInc
self . _ yC oor d += yInc
85 / 180
Classes
Usando mdulos
p1 = P o n t o ( 5 , 7 )
p2 = P o n t o ( 0 , 0 )
x = p1.getX()
y = p1.getY()
print( "(" + str(x) + " , " + str(y) + ")" )
p 1 . s h i f t ( 4 , 12)
d = p1.distancia(p2)
86 / 180
Classes
Escondendo a t r i b u t o s
87 / 180
Classes
Escondendo a t r i b u t o s
>>> p = P o n t o ( 2 . 0 , 2 . 0 )
>>> p r i n t p.xcoord
2.0
>>> p.xCoord = z e b r a
>>> p r i n t p.xCoord
zebra
Oi d e a l que o us u r i o s a l t e r e o estado do
o b j e t o a t r a v s de mtodos que operem sobre o
mesmo, e no manipulando os seus a t r i b u t o s . 88 / 180
Classes
Escondendo a t r i b u t o s
def p o n t o A ( s e l f ) :
return s e l f . pontoA
def p o n t o B ( s e l f ) :
return s e l f . pontoB
def com pr im en t o ( s e l f ) :
return s e l f . pontoA.distancia( self . pontoB)
def e h V e r t i c a l ( s e l f ) :
r e t u r n s e l f . pontoA.getX () == s e l f . pontoB . getX ()
Exempl o
>>> p1 = P o n t o ( 1 . 0 , 1 . 0 )
>>> p2 = P o n t o ( 0 . 0 , 0 . 0 )
>>> p 2 . s h i f t ( 1 . 0 , 1 . 0 )
>>> i f p1 == p2:
... p r i n t "Os pontos sao i g u a i s . "
90 / 180
Classes
Sobrecarga de operadores
class Ponto:
# ...
def str ( s e l f ) :
r e t u r n " ( %f , %f ) " % ( s e l f . x C o o r d , s e l f . yC o o r d )
# ...
>>> p = P o n t o ( 1 . 5 , 2 . 5 )
>>> p r i n t p
( 1 . 5 0 0 0 0 0 , 1.500000 )
91 / 180
Classes
Sobrecarga de operadores
92 / 180
Programao Funcional
Alm de s u p o r t a r programao e s t r u t u r a d a e
o r i e n t a o a o b j e t o s , Python tambm possui
recursos de programao f u n c i o n a l .
Vamos a p r e s e n t a r de forma p r t i c a alguns destes
mecanismos:
Funes lambda
map, f i l t e r e reduce
Existem muitos outr os recursos de programao
f u n c i o n a l como i t e r a t o r s e g e n e r a t o r s , que no
teremos tempo de d i s c u t i r .
93 / 180
Programao Funcional
map
94 / 180
Programao Funcional
map
95 / 180
Programao Funcional
filter
>>> def f ( ) : r e t u r n x % 2 == 0
>>> p r i n t f i l t e r ( f , r a n g e ( 5 ) )
[ 0 , 2, 4]
96 / 180
Programao Funcional
reduce
97 / 180
Programao Funcional
#map
seq = [ ]
f o r num i n r a n g e ( 5 ) :
seq = seq + [num * num]
p r i n t seq
#filter
seq = [ ]
f o r num i n r a n g e ( 5 ) :
i f num % 2 == 0 :
seq = seq + [num]
p r i n t seq
#reduce
total = 0
f o r num i n r a n g e ( 5 ) :
t o t a l = t o t a l + (num * num)
print total
98 / 180
Programao Funcional
99 / 180
Programao Funcional
100 / 180
Programao Funcional
101 / 180
Ar qui vos
102 / 180
Ar qui vos
o u t f i l e . w r i t e ( N o t a s da P r o va \ n )
o u t f i l e . w r i t e ( - * 40 + \ n )
f o r e i n e s tuda nte s :
o u t f i l e . w r i t e ( % s \ t %6.2f \ n % (e.nom e, e . n o t a ) )
o u t f i l e . w r i t e ( - * 40 + \ n )
outfile.close
p r e c i s o e x p l i c i t a m e n t e c o l o c a r para quebra de
l i n h a no comando w r i t e , di fe r e nte me nte de p r i n t
103 / 180
Ar qui vos
104 / 180
Ar qui vos
Ou podemos quebrar a l i n h a em v r i a s p a r t e s
# l i n h a s no formato
# nome idade nota
line = infile.readline()
temp = l i n e . s p l i t ( )
nome, i d a d e , nota = t e m p [ 0 ] , t e m p [ 1 ] , temp[2]
105 / 180
EXERC CI O
106 / 180
EXERC CI O
107 / 180
EXERC CI O
Uma p o s s v e l soluo
def l e _ p o n t o s ( a r q u i vo ) :
l = []
f = open (ar quivo, r )
line = f.readline()
# l e numero de pontos
total = int(line)
# l e os pontos e coloca na l i s t a l
for i in range(total):
line = f.readline()
temp = l i n e . s p l i t ( )
p = Ponto(float(temp[0]), float(temp[1]))
l.append(p)
f.close()
return l
108 / 180
Parte I I I
Computao C i e n t f i c a com Python
109 / 180
Workflow C i e n t f i c o
110 / 180
O que NumPy?
Numerical Python
B i b l i o t e c a para manipulao de a r r a ys
mul ti di me ns i ona i s e m a t r i z e s .
Operaes r p i d a s em a r r a ys (fun e s
vetorizadas)
D i f e r e n a com r e l a o a l i s t a s t r a d i c i o n a i s do
Python
Vetor homogneo
Muito mais e f i c i e n t e s do que as l i s t a s
Nmero de elemento deve ser conhecido a p r i o r i . O
a r r a y pode ser redimensionado posteriormente .
Muito e f i c i e n t e (implementado em C)
111 / 180
Python Puro VS NumPy
112 / 180
Criando vetores NumPy
113 / 180
Criando vetores NumPy
>>> az = n p . z e r o s ( 4 ) # dtype = n p . f l o a t 6 4
>>> az
array([ 0 . , 0 . , 0 . , 0 . ] )
>>> a = n p . a r a n g e ( 0 . 0 , 1 . 0 , 0 . 2 ) # dtype = n p . f l o a t 6 4
>>> a
array([ 0 . , 0.2, 0.4, 0.6, 0.8])
114 / 180
Criando vetores NumPy
>>> a = n p . l i n s p a c e ( 0 . 0 , 1 . 0 , 6 )
>>> p r i n t a
[ 0. 0.2 0.4 0.6 0.8 1 . ]
>>> p r i n t a . s i z e , a.ndim , a.shape # a t r i b u t o s importantes
6 1 (6,)
>>> m = a . r e s h a p e ( 2 , 3 )
>>> p r i n t m
[ [ 0. 0.2 0.4]
[ 0.6 0.8 1 . ] ]
>>> p r i n t m . s i z e , m.ndim, m.shape
6 2 ( 2 , 3)
>>> Z = n p . z e r o s ( ( 3 , 3 ) )
>>> p r i n t Z
[ [ 0. 0. 0.]
[ 0. 0. 0.]
[ 0. 0. 0 . ]]
115 / 180
Acessando arrays
116 / 180
Acessando arrays
117 / 180
Acessando arrays
118 / 180
Acessando arrays
119 / 180
Acessando arrays
120 / 180
Acessando arrays
>>> a = np.ar ange(24)
>>> a = a . r e s h a p e ( ( 4 , 6 ) )
>>> a [ 2 , 4 ]
16
>>> a [ 1 ] # ou a [ 1 , : ]
array([ 6 , 7, 8, 9 , 10, 11])
>>> a [ - 1 ]
a r r a y([ 1 8 , 19, 20, 21, 22, 23])
>>> a [ : , 1 ]
array([ 1 , 7 , 13, 19])
>>> a [ 1 : 3 , : ]
array([[ 6, 7, 8, 9 , 10, 11],
[12, 13, 14, 15, 16, 1 7 ] ] )
>>> a [ 1 : 4 , 2 : 5 ]
array([[ 8, 9, 10],
[14, 15, 16],
[20, 21, 2 2 ] ] )
121 / 180
Acessando arrays
>>> a = np.ar ange(24)
>>> a = a . r e s h a p e ( ( 4 , 6 ) )
>>> a [ 2 , 4 ]
16
>>> a [ 1 ] # ou a [ 1 , : ]
array([ 6 , 7, 8, 9 , 10, 11])
>>> a [ - 1 ]
a r r a y([ 1 8 , 19, 20, 21, 22, 23])
>>> a [ : , 1 ]
array([ 1 , 7 , 13, 19])
>>> a [ 1 : 3 , : ]
array([[ 6, 7, 8, 9 , 10, 11],
[12, 13, 14, 15, 16, 17]])
>>> a [ : : 2 , : : 3 ]
array([[ 0, 3],
[12, 15]])
122 / 180
Operaes com arrays
123 / 180
Operaes com arrays
Outras operaes
>>> a = n p . a r r a y ( [ 1 , 0 , 1 ] )
>>> b = n p . a r r a y ( [ 2 , 2 , 4 ] )
>>> n p . d o t ( a , b )
6
>>> a = n p . a r r a y ( [ 1 , 0 , 0 ] )
>>> b = n p . a r r a y ( [ 0 , 1 , 0 ] )
>>> n p . c r o s s ( a , b )
ar r ay([0, 0 , 1 ] )
>>> a , b = n p . a r r a y ( [ 1 , 2 , 3 ] ) , n p . a r r a y ( [ 1 , 2 , 3 ] )
>>> n p . o u t e r ( a , b )
array([[1, 2, 3 ] ,
[2, 4, 6],
[3, 6, 9]])
124 / 180
Funes e Arrays NumPy
A v a l i a r funes usando
a r r a ys NumPy
from math import exp, s i n
Exempl o: () = ( ) import numpy as np
lentos x = n p . l i n s p a c e ( 0 . 0 , 6 . 0 , 100)
y = np.zeros(x.size)
Alternativas:
Vectorization for i in range(x.size):
NumPy oferece y[i] = f(x[i])
diversas funes
prontas
125 / 180
Vectorization
Apl i c a r di r e ta me nte
em todo o v e t o r
M uito mais e f i c i e n t e # importa versoes numpy de exp e s i n
import numpy as np
Mais compacto e f c i l
de l e r def f ( x ) :
return np.exp(np.sin(x))
Nem todas funes d e f
f u n c ( x ) esto prontas x = l i n s p a c e ( 0 . 0 , 6 . 0 , 1000)
y = f(x)
para serem usadas
desta forma
126 / 180
Vectorization
Apl i c a r di r e ta me nte
em todo o v e t o r
M uito mais e f i c i e n t e # importa versoes numpy de exp e s i n
import numpy as np
Mais compacto e f c i l
de l e r def f ( x ) :
return np.exp(np.sin(x))
Nem todas funes d e f
f u n c ( x ) esto prontas x = l i n s p a c e ( 0 . 0 , 6 . 0 , 1000)
y = f(x)
para serem usadas
desta forma
# funcao degrau
def H ( x ) :
i f (x < 0 ) :
return 0
else
return 1
127 / 180
Vectorization
>>> x = l i n s p a c e ( - 1 , 1 , 5 )
array([-1. , - 0 . 5 , 0. , 0.5, 1. ])
>>> x < 0
a r r a y( [ True, True, False, False, False])
128 / 180
Vectorization
Forma g e r a l
def f u n _ ve c ( x ) :
cond = <exp _ condicao>
x1 = <expressao1>
x2 = <expressao2>
r e t u r n where(cond, x 1 , x 2 )
def H v ( x ) :
cond = x < 0
r e t u r n where(cond, 0 . 0 , 1 . 0 )
129 / 180
Alguns mtodos dos vetores
130 / 180
Copiando Arrays
131 / 180
Mat r i zes
132 / 180
Mat r i zes
133 / 180
Mat r i zes e lgebra Linear
Soluo >>> A = n p . m a t r i x ( [ [ 3 . , 2 . , 4 . ] , [ 1 . , 1 . , 2 . ] , [ 4 . , 3 . , - 2 . ] ] )
>>> A
de matrix([[ 3 . , 2 . , 4.],
Sistema [ 1., 1., 2.],
[ 4., 3., -2.]])
de
Equaes >>> b = n p . m a t r i x ( [ [ 1 . ] , [ 2 . ] , [ 3 . ] ] )
Li near es >>> b
matrix([[ 1 . ] ,
[ 2.],
[ 3.]])
++=
++=
>>> x = l i n a l g . s o l v e ( A , b )
>>> x
+=
matrix([[-3.],
[ 5.],
[ 0.]])
134 / 180
Pol i nmi os
NumPy d e f i n e um >>> f = n p . p o l y 1 d ( [ 4 , 2 , - 1 ] )
>>> f ( 3 )
t i p o para 41
polinmios
>>> p r i n t f
Operaes 2
aritmticas e 4 x + 2 x - 1
135 / 180
Ajuste de Curvas
136 / 180
Ajuste de Curvas
>>> x = n p . a r r a y ( [ 0 . 0 , 1 . 0 , 2 . 0 ,
3.0, 4.0, 5.0])
>>> y= n p . a r r a y ( [ 0 . 0 , 0 . 8 , 0 . 9 ,
0.1, -0.8, -1.0])
>>> c1 = n p . p o l y f i t ( x , y , 1 )
>>> c1
a r r a y( [ - 0 . 3 0 2 8 5 7 1 4 , 0 . 7 5 7 1 4 2 8 6 ] )
137 / 180
Sci Py
138 / 180
Integrao Numrica com SciPy
?
Exemplo:
>>> i n t e g r a t e . q u a d ( f x 2 , 0 . 0 , 4 . 0 )
(21.333333333333332, 2.3684757858670003e -13)
>>> p r i n t 4 . * * 3 / 3
21.3333333333
139 / 180
Integrao Numrica com SciPy
Mais mtodos d i s p o n v e i s
fixed _ quad: quadratura Gaussiana
o d e i n t : i n t e g r a r Equaes D i f e r e n c i a i s
Ordinrias
I n t e g r a r um conjunto de dados d i s c r e t o s
t r a p z , simps e romb
>>> x = l i n s p a c e ( 0 . 0 , 4 . 0 , 2 5 )
>>> y = f x 2 ( x )
array([ 0 . , 0.16666667, 0.33333333, 0.5 , 0. 66666667,
0.83333333, 1. , 1.16666667, 1.33333333, 1.5 ,
1.66666667, 1.83333333, 2 . , 2.16666667, 2. 33333333,
2.5 , 2.66666667, 2.83333333, 3. , 3. 16666667,
3. 33333333, 3. 5 , 3. 66666667, 3. 83333333, 4.
])
>>> i n t e g r a t e . t r a p z ( y , d x = x [ 1 ] - x [ 0 ] )
21.351851851851851
140 / 180
Processamento D i g i t a l de Imagens (ndimage)
>>> s h i f t e d _ l e n a = n d i m a g e . s h i f t ( l e n a , ( 5 0 , 5 0 ) )
>>> s h i f t e d _ l e n a 2 = n d i m a g e . s h i f t ( l e n a , ( 5 0 , 5 0 ) , mode=near est )
>>> r o t a t e d _ l e n a = n d i m a g e . r o t a t e ( l e n a , 3 0 )
>>> cropped _ lena = l e n a [ 5 0 : - 5 0 , 5 0 : - 5 0 ]
>>> zoomed _ lena = ndimage.zoom(lena, 2 )
>>> zoomed _ lena.shape
( 1 0 2 4 , 1024)
141 / 180
Processamento D i g i t a l de Imagens
>>> lena = s c i p y . l e n a ( )
>>> import numpy as np
# aplica f i l t r o s
142 / 180
Visualiz a o de dados com m a t p l o t l i b
A b i b l i o t e c a m a t p l o t l i b pe r mi te a v i s u a l i z a o
de dados 2D seguindo o e s t i l o do MATLAB
G r f i c o s de qua l i da de para publicaes
Exporta para di ve r s os formatos
P o s s i b i l i d a d e de embutir em i n t e r f a c e s g r f i c a s
( Q t , GTK, . . . )
Baseado no NumPy e SciPy
p y l a b : mdulo com d i v e r s a s funes para p l o t a r
g r f i c o s de forma f c i l
143 / 180
mat pl ot l i b
>>> x = l i n s p a c e ( 0 , 3 , 5 1 )
>>> y = x * * 2 * e x p ( - x * * 2 )
>>> p l o t ( x , y )
[<matplotlib. lines.Li ne2D o b j e c t . . . ]
>>> show()
144 / 180
mat pl ot l i b
Decorando o g r f i c o
>>> x = l i n s p a c e ( 0 , 3 , 5 1 )
>>> y = x * * 2 * e x p ( - x * * 2 )
>>> p l o t ( x , y )
>>> grid(True)
>>> xlabel(x)
>>> ylabel ( f (x ) )
>>> title("Exemplo" )
>>> show()
145 / 180
mat pl ot l i b
V r i a s curvas
>>> y = l i n s p a c e ( - 3 , 3 , 1 0 )
>>> p l o t ( y )
>>> x = l i n s p a c e ( 0 , 9 , 100)
>>> plot(x,sin(x))
>>> plot(x,cos(x), r - - )
>>> p l o t ( x , e x p ( s i n ( x ) ) , m - . )
>>> grid(True)
>>> show()
146 / 180
mat pl ot l i b
Controlando o e s t i l o do p l o t
A funo p l o t a c e i t a uma s t r i n g e s pe c i fi c a ndo o
e s t i l o da l i n h a e do smbolo usando o s e gui nte
f o r m a t o : < c o l o r > < l i n e > <s ym b o l >
Cores
r vermelho c ciano
g verde m magenta
b azul y amarel o
w branco k preto
Smbolos
. pontos o circulo t r i a n g u l o baixo
s quadrados + cruz t r i a n g u l o cima
x "xis" * estrela < t r i a n g u l o esq
D diamante d d i amante p e q . > triangulo d i r
Est i l o da L i n h a
- solid line
- dashed l i n e
-. dash-dot l i n e
: dotted l i n e
147 / 180
mat pl ot l i b
>>> x = l i n s p a c e ( - 6 , 6 , 500)
>>> plot(x,sin(x), label=sin(x))
>>> plot(x,cos(x), label=cos(x))
>>> t i t l e ( S e n o e Cosseno)
>>> xlabel(x)
>>> ylabel ( f (x ) )
>>> axis([-6,6,-2,2])
>>> legend(loc= "upper r i g h t " )
148 / 180
mat pl ot l i b
Histogramas
h i s t ( x , bins=10)
D i s t r i b u i o normal (,)
149 / 180
mat pl ot l i b
G r f i c o de b a r r a s
bar(x, height): p l o t a um g r f i c o de b a r r a s com
retngulos
xticks(x, labels): pos i c i ona r t u l o s dos
retngulos
>>> x = [ 1 , 2 , 3 , 4 , 5 , 6 ]
>>> y = [ 5 , 8 , 1 5 , 2 0 , 1 2 , 1 8 ]
>>> b a r ( x , y , a l i g n = c e n t e r ,
color = #2090AA )
>>> l a b = (" D 1" , " D 2" , " D 3 " , " D 4" , " D 5" , " D 6" )
>>> x t i c k s ( x , l a b )
150 / 180
mat pl ot l i b
Salvando os g r f i c o s em f i g u r a s
savefig(filename):
Salva a f i g u r a a t u a l usando o f o r m a t o .
Alguns parmetros o p c i o n a i s :
format: p n g , p d f , p s , e p s , svg
t r a n s p a r e n t : True ou False
151 / 180
G a l e r i a do m a t p l o t l i b
152 / 180
G a l e r i a do m a t p l o t l i b
153 / 180
Gal er i a do m a t p l o t l i b
154 / 180
Exemplo Completo
?( ) =(( ), )
dada a condio I n i c i a l
()=
?( ) =
155 / 180
Exemplo Completo
Mtodo de E u l e r E x p l c i t o
+ = + (, )
onde:
a aproximao numrica da soluo exata ( )
no tempo
o passo de tempo
= , =,. . . ,
( ) =
156 / 180
Exemplo Completo - Algoritmo
Dado: , , ,
C a l c ul a r (nmero de passos de tempo)
Para k de 0 a t n f a a
Calcular + usando
+ = + (, )
E x i b i r os r e s u l t a d o s
157 / 180
Exemplo Completo - Python
?( ) =, =, =
# i n i c i a l i z a vetor es print v
u = z er os ( n + 1 ) print u
v = z er os ( n + 1 )
t = z er os(n+ 1 ) # exibe g r a f i c o da solucao
plot(t,v, r - , label=exata)
# condicao i n i c i a l p l o t ( t , u , b - - , label=aproximada)
t [ 0 ] = 0.0 legend(loc= " upper l e f t " )
u [ 0 ] = u0 show()
158 / 180
Exemplo Completo
159 / 180
Exemplo Completo com SciPy
scipy.integrate.odeint(func, y0, t)
Usa a b i b l i o t e c a odepack e s c r i t a em FORTRAN.
T = 3.0
u0 = 1.0
dt = 0.01
n = int(T/dt)
def f ( u , t ) :
return u
t = np.linspace(0.0, T, n)
u = odeint(f,u0,t)
plot(t,u)
160 / 180
Parte I V
Outras b i b l i o t e c a s e p r o j e t o s com Python
161 / 180
Bi bl i ot ecas
De uso g e r a l
Redes
Games
I n t e r f a c e s Grficas
Tratamento de Imagens
Banco de Dados
etc, etc, etc.
Computao C i e n t f i c a
Computao Simblica
Visualiz ao
Computao G r f i c a
Soluo de Equaes D i f e r e n c i a i s P a r c i a i s
etc, etc, etc.
162 / 180
PyGame
Mdulo m u l t i p l a t a f o r m a p r o j e t a d o para e s c r e ve r
jogos.
B i b l i o t e c a s de computao g r f i c a e som
includas.
163 / 180
Net wor kX
http://networkx.lanl.gov/
E s t r u t u r a s de dados para g r a f o s , d i g r a f o s e
multigrafos.
Algoritmos c l s s i c o s de g r a f o s .
Adequada para operaes em grandes g r a f o s .
Pode s e r usada para a n l i s e de r e d e s .
164 / 180
Pyt hon Imaging L i b r a r y
h t t p : / / w w w . p yt h o nw a r e . c om / p r o du c ts / p i l
Processamento de imanges.
Suporte a di ve r s os formatos e possui d i v e r s a s
ferramentas.
165 / 180
PyQt
166 / 180
Databases
c = conn.cursor()
# Create t a b l e
c.execute(CREATE TABLE stocks
( d a t e t e x t , t r a n s t e x t , symbol t e x t , qty r e a l , p r i c e real) )
# I n s e r t a row o f data
c.execute("INSERT INTO stocks VALUES
(2006-01-05,BUY,RHAT,10,5.14)" )
h t t p : / / w w w s e a r c h. s o u r c e f or g e . n e t / m e c h a n i z e /
br = mechanize.Browser()
br . open(" http: //w ww .exam p le. com / " )
# f o l l o w second l i n k with element t e x t matching r e g u l a r expression
response1 = b r . f o l l o w _ l i n k ( t e x t _ r e g e x = r " c h e e s e \ s * s h o p " , n r = 1 )
a s s e r t b r . vi e w i n g _ h t m l ( )
print b r . t i t l e ( )
p r i n t response1.geturl()
p r i n t r e s p o n s e 1 . i n f o ( ) # headers
p r i n t r esponse1.r ead() # body
168 / 180
B i b l i o t e c a s para Computao C i e n t f i c a
169 / 180
Sympy
Computao Simblica
A l t e r n a t i v a l i v r e aos s oftw ar e s M a pl e ,
Mathematica e M a t l a b .
A r i t m t i c a b s i c a , expanses, fun e s ,
derivadas, i n t e g r a i s , substituies, l i m i t e ,
matrizes, e t c .
170 / 180
Sage
171 / 180
Visualiz a o C i e n t f i c a
MayaVi
172 / 180
Comput ao Gr f i ca, Vi sual i zao
Computao g r f i c a ,
processamento de imagens e
visualizao.
E s c r i t o em C++ com i n t e r f a c e
em T c l / T k , Java e Python. PyOpenGL: bi ndi ng
de OpenGL para
Python
OpenGL: API l i v r e
u t i l i z a d a na
computao g r f i c a
173 / 180
l gebr a Li near Computacional
Al g e b r a i c M u l t i g r i d S ol ve r s PySparse:
i n Python B i b l i o t e c a para
D i ve r s a s implementaes do m a t r i z e s esparsas
AMG Diversos f o r m a t o s .
F c i l de u s a r , r p i d o , Converso
eficiente S ol v e r s i t e r a t i v o s
Pr econdi ci onador es
h t t p : / / c o d e . g o o g l e . c o m / p / p ya m g /
ht t p: / / pyspar se. sour cef or ge. net /
174 / 180
Soluo Numrica de Equaes D i f e r e n c i a i s
FEniCS P r o j e c t
Soluo automatizada
de EDPs usando o FiP y (A f i n i t e volume
mtodo dos elementos PDE s o l v e r w r i t t e n i n
finitos Python)
Al t o n v e l de S o l v e r de EDPs usando
abstrao ( M u i t o o mtodo dos volumes
prximo da formulao finitos
matemtica) Orientado a o b j e t o s
Paralelismo, Computao p a r a l e l a
adaptatividade,
e s t i m a t i v a s de e r r o .
175 / 180
Apr edi z agem de Mquina
Scikits
Construdo sobre
Shogun: A Large Scale NumPy, SciPy e
Machine Learning Matplotlib
Toolbox
Di ve r s a s t c n i c a s como
SVM (S uppor t V e c tor SVM, K-Means, e t c
Machines)
http://www.shogun-toolbox.org/
http://scikit-learn.sourceforge.net
176 / 180
Python para F s i c a
As t r o p ys i c s :
ht t p: / / packages. pyt hon. or g/ Ast r opysi cs/
U t i l i t r i o s de a s t r o f s i c a em Python
PyFITS: h t t p : / / p a c k a g e s . p y t h o n . o r g / p y f i t s /
Manipulao de imagens FITS em Python
YT: h t t p : / / y t - p r o j e c t . o r g /
yt umt o o l k i t para manipular dados de simulaes
a s t r o f s i c a s com suporte para a n l i s e e
visualizao.
177 / 180
Python para Qumica
Cheminformatics: OpenBabel ( P y b e l ) , R D K i t ,
OEChem, D a y l i g h t ( P y D a y l i g h t ) , Cambios M ol e c ul a r
T o o l k i t , Frow ns, PyBabel and M o l K i t
Computational c h e m i s t r y: OpenBabel, c c l i b ,
QMForge, GaussSum, PyQuante, NWChem,
M a e s t r o/ J a g ua r , MMTK
Visualisation: CCP1GUI, PyMOL, PMV, Z e o b u i l d e r ,
Chimera, VMD
178 / 180
The Zen o f Python
B e a u t i f u l i s b e t t e r than u g l y .
E x p l i c i t i s b e t t e r than i m p l i c i t .
Simple i s b e t t e r than complex.
Complex i s b e t t e r than com plic a te d .
F l a t i s b e t t e r than n e s t e d .
Sparse i s b e t t e r than dense.
R e a d a b i l i t y counts.
S p e c i a l cases a r e n t s p e c i a l enough t o break t h e r u l e s .
Although p r a c t i c a l i t y beats p u r i t y .
E r r o r s should never pass s i l e n t l y .
Unless e x p l i c i t l y s i l e n c e d .
I n t h e f a c e o f a m b i g u i t y, r e f u s e t h e tem ptation t o guess.
There should be one- and p r e f e r a b l y only one -obvious way t o do i t .
Although t h a t way may not be obvious a t f i r s t unless yo u r e Dutch. Now
i s b e t t e r than n e ve r .
Although never i s o f t e n b e t t e r than * r i g h t * now.
I f t h e implementation i s hard t o e x p l a i n , i t s a bad i d e a .
I f t h e implementation i s easy t o e x p l a i n , i t may be a good i d e a .
Namespaces a r e one honking g r e a t i d e a - l e t s do more o f t h o s e !
179 / 180
Referncias e Agradecimentos
S l i d e s de R a f a e l Sachetto O l i v e i r a (UFSJ)
Mais informaes:
http://w ww.python.org
h t t p :/ / num py. o r g
http://fperez.org/py4science/
Equipe da Semana da Computao (USP - So
Carlos)
180 / 180