Sei sulla pagina 1di 180

Introduo programao com Python

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

Departamento de Computao e Mecnica


CEFET-MG Campus L e o p o l d in a

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

Python uma linguagem i n t e r p r e t a d a


No e x i s t e uma etapa de compilao do c d i g o ,
como em C/C++, F o r t r a n
Voc simplesmente executa o comando python e
pode comear a e x e c uta r cdigo de forma
interativa

8 / 180
Vamos comear

Python uma linguagem i n t e r p r e t a d a


No e x i s t e uma etapa de compilao do c d i g o ,
como em C/C++, F o r t r a n
Voc simplesmente executa o comando python e
pode comear a e x e c uta r cdigo de forma
interativa
rocha@machine:~/Desktop\$ python

Python 2 . 6 . 6 ( r 2 6 6 : 8 4 2 9 2 , Sep 15 2010, 1 5 : 5 2 : 3 9 )


[GCC 4 . 4 . 5 ] on l i n u x 2
Type h e l p , c o p yr i g h t , c r e d i t s or l i c e n s e f o r more i n f o . .

>>>

>>> 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 >

Podemos e x e c uta r c di gos :


de forma i n t e r a t i v a usando o i n t e r p r e t a d o r
python, como no exemplo acima
ou atravs da l i n h a de comando ( d o i s c l i q u e s ) :
python programa.py
./programa.py

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

>>> c = " 5"


>>> q = 4
>>> c, q = q, c
>>> print c, q
4 5

>>> 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

>>> c = " 5"


>>> q = 4
>>> c, q = q, c
>>> print c, q
4 5

>>> 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

I s t o , Python uma linguagem di n mi c a , mas com


tipagem f o r t e , ao c o n t r r i o de o u t r a s linguagens
como P e r l que dinmica e com tipagem f r a c a .

14 / 180
St r i ngs

Python d e f i n e umt i p o de dados n a t i v o para


strings ( s t r )
S t r i n g s podem s e r d e l i m i t a d a s por aspas s i m p l e s ,
dupla ou t r i p l a

15 / 180
St r i ngs

Python d e f i n e umt i p o de dados n a t i v o para


strings ( s t r )
S t r i n g s podem s e r d e l i m i t a d a s por aspas s i m p l e s ,
dupla ou t r i p l a

>>> s i m p l e s
simples

>>> "dupla"
dupla

>>> " " " t r i p l a " " "


tripla

>>> " " " t r i p l a possui uma propriedade e s p e c i a l : e l a s


ignoram quebra de l i n h a , por tanto a s t r i n g aparece como e l a
eh e s c r i t a " " "
t r i p l a possui uma propriedade e s p e c i a l : e l a s \ n ignoram

16 / 180
St r i ngs

>>> 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 " )


C: \ di r et or i o
ovo
ada.exe

Como e v i t a r a quebra de l i n h a ?

17 / 180
St r i ngs

>>> 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 " )


C: \ di r et or i o
ovo
ada.exe

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

>>> 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 " )


C: \ di r et or i o
ovo
ada.exe

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

Ooperador + no c onve r te automaticamente


nmeros ou outr os t i p o s em s t r i n g s . A funo
s t r ( ) c onve r te v a l o r e s para sua representao em
string.
>>> p i = 3 . 1 4
>>> t e x t = o va l o r de p i eh = + p i
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 f l o a t obj ects

>>> t e x t = o va l o r de p i eh = + str(pi)

21 / 180
St r i ngs

Ooperador + no c onve r te automaticamente


nmeros ou outr os t i p o s em s t r i n g s . A funo
s t r ( ) c onve r te v a l o r e s para sua representao em
string.
>>> p i = 3 . 1 4
>>> t e x t = o va l o r de p i eh = + p i
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 f l o a t obj ects

>>> 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]

>>> s = " h e l l o "


>>> s [ 0 ]
h
>>> s [ 1 : ]
ello
>>> s [ 1 : 4 ]
ell
>>> s [ : ]
hello
>>> s [ 1 : 1 0 0 ]
ello

23 / 180
Strings - Mtodos

S t r i n g s possuem uma grande va r i e da de de 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

S t r i n g s possuem uma grande va r i e da de de 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

S t r i n g s possuem uma grande va r i e da de de 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

Uma t u p l a uma coleo de o b j e t o s separados por


vrgula
>>> primos = ( 2 , 3 , 5 , 7 )
>>> p r i n t p r i m o s [ 0 ] , p r i m o s [- 1 ]
2 7

>>> 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

Para uma t u p l a com 1 elemento apenas p r e c i s o


usar ( v a l , )

29 / 180
Tupl as

Pode t e r ou no parnteses para d e l i m i t a r a


tupla
Tupla aninhada
Heterognea

>>> t = 12345, 54321, h e l l o ! # ou


>>> t = ( 1 2 3 4 5 , 5 4 3 2 1 , h e l l o )
>>> t [ 0 ]
12345
>>> t
( 1 2 3 4 5 , 54321, h e l l o ! )

>>> u = t , ( 1 , 2 , 3 , 4 , 5 ) # t u p l a s podem ser aninhadas


>>> u
( ( 1 2 3 4 5 , 54321, h e l l o ! ) , ( 1 , 2 , 3 , 4 , 5 ) )

>>> 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

As l i s t a s contm p o n t e i r o s para o b j e t o s que


residem em algum l u g a r na memria.

33 / 180
Lista
Representao

As l i s t a s contm p o n t e i r o s para o b j e t o s que


residem em algum l u g a r na memria.

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

A linguagem Python automaticamente importa


algumas fun e s , t i p o s e smbolos que so
conhecidos como b u i l t - i n s .
Mecanismos bsicos da linguagem.

39 / 180
Built-ins

A linguagem Python automaticamente importa


algumas fun e s , t i p o s e smbolos que so
conhecidos como b u i l t - i n s .
Mecanismos bsicos da linguagem.

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 )

Help on b u i l t - i n f u n c t i o n range i n module builtin :

range(...)
r ange([star t , ] stop[, step]) -> l i s t of integers

Return a l i s t contain in g an a r i t h m e t i c progression o f i n t e g e r s .


r a n g e ( i , j ) returns [ i , i + 1 , i + 2 , . . . , j - 1 ] ; s t a r t ( ! ) defaults to 0 .
When step i s g i ve n , i t s p e c i f i e s t h e increment ( o r decr em ent).
For example, r a n g e ( 4 ) r e t u r n s [ 0 , 1 , 2 , 3 ] . The end p o i n t i s o m i t t e d !
These a r e e x a c t l y t h e v a l i d i n d i c e s f o r a l i s t o f 4 el em ents.

43 / 180
A funo range

>>> h e l p ( r a n g e )

Help on b u i l t - i n f u n c t i o n range i n module builtin :

range(...)
r ange([star t , ] stop[, step]) -> l i s t of integers

Return a l i s t contain in g an a r i t h m e t i c progression o f i n t e g e r s .


r a n g e ( i , j ) returns [ i , i + 1 , i + 2 , . . . , j - 1 ] ; s t a r t ( ! ) defaults to 0 .
When step i s g i ve n , i t s p e c i f i e s t h e increment ( o r decr em ent).
For example, r a n g e ( 4 ) r e t u r n s [ 0 , 1 , 2 , 3 ] . The end p o i n t i s o m i t t e d !
These a r e e x a c t l y t h e v a l i d i n d i c e s f o r a l i s t o f 4 el em ents.

>>> r ange (10 )


[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> r a n g e ( 1 0 , 2 0 )
[ 1 0 , 11, 12, 13, 14, 15, 16, 17, 18, 19]
>>> r a n g e ( 1 0 , 2 0 , 2 )
[ 1 0 , 12, 14, 16, 18]
>>> r a n g e ( 2 0 , 1 0 , - 1 )
[ 2 0 , 19, 18, 17, 16, 15, 14, 13, 12, 11]

44 / 180
bool

Tipo de dados bool


T r u e , F a l s e e None
Operadores: i s , n o t , a nd, o r
>>> x = 11
>>> x > 0
True
>>> x % 2 == 0
False

>>> y = True
>>> not y
False

>>> x i s not None


True

45 / 180
I ndent ao

Aviso aos navegantes!


Python no usa { , } , b e g i n , end para e s t r u t u r a de
bloco
Cdigo em C

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

Aviso aos navegantes!


Python no usa { , } , b e g i n , end para e s t r u t u r a de
bloco
Cdigo em C

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

Emg e r a l programadores Python usam 4 espaos em


branco ou 2 , o i mpor ta nte s e r c o n s i s t e n t e .
49 / 180
Est r ut ur as de Controle
If-elif-else

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

>>> i f ( ( x >= 0 ) and ( x <= 1 0 0 ) ) :


If-Else-If-Else ... p r i n t "OK"
. . . else:
i f exp:
... p r i n t "Fora do i n t e r v a l o "
comandos
e l i f exp:
>>> i f ( ( x < 0 ) or ( x > 1 0 0 ) ) :
comandos
... p r i n t "Fora do i n t e r v a l o "
else:
. . . else:
comandos
... p r i n t "OK"

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()

A funo e nume r a te () c r i a pares u t e i s

>>> 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)

>>> f o r i,nome i n enumerate(nomes):


... p r i n t i,nome
1 Ana
2 Maria
3 C lar a

55 / 180
Outras construes para loops
zip()

A funo z i p ( ) recebe umpa r de sequncias como


e ntr a da e c r i a uma t u p l a com os seus elementos

>>> 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

Python no possui uma e s t r u t u r a do t i p o s w i t c h ,


como C , C++ e J a v a .
Podemos c ontor na r a s i t u a o com uma c a de i a de i f -
elses

>>> 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 )

Funo >>> def f i b ( n ) :


def nome1(arg1, a r g 2 , . . . ) : ... " " " Imprime a t e n . " " "
comandos ... a, b = 0, 1
r e t u r n expressao ... while a < n :
... print a,
def nome2(arg1, a r g 2 , . . . ) : ... a , b = b , a+b
comandos
>>> p a r ( 6 ) # True
r e t u r n exp1, exp2, exp3
>>> f i b ( 8 ) # 01 12 3 5
def nome3(arg1, a r g 2 , a r g x = va l o r ) :
comando
r e t u r n exp

59 / 180
Funes

Podemos c r i a r funes com parmetros opc i ona i s


que possuem um v a l o r d e f a u l t p r - d e f i n i d o

>>> def m u l t ( x , num=2):


... r e t u r n x , x*num

>>> 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 )

Help on f u n c t i o n d i vi d e i n module main :

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

Escreva uma funo que dada uma s t r i n g que


r e p r e s e n t a uma URL de uma pgina da web, o b t e r
apenas o endereo da pgina p r i n c i p a l .
Exemplo:
>>> u r l _ p a r s e ( h t t p : / / w w w . f a c e b o o k . c o m / f u l a n o / p h o t o s )
www.facebook.com

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

if name == " main ":

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

D i c i o n r i o uma e s t r u t u r a de dados muito t i l


que pe r mi te armazenar e r e c upe r a r pares de
chaves-e-valores.
Arrays a s s o c i a t i v o s .
De forma g r o s s e i r a podemos d i z e r que um d i c i o n r i o
uma l i s t a que podemos acessar seus elementos
a t r a v s de s t r i n g s .

68 / 180
Di ci onr i o

D i c i o n r i o uma e s t r u t u r a de dados muito t i l


que pe r mi te armazenar e r e c upe r a r pares de
chaves-e-valores.
Arrays a s s o c i a t i v o s .
De forma g r o s s e i r a podemos d i z e r que um d i c i o n r i o
uma l i s t a que podemos acessar seus elementos
a t r a v s de s t r i n g s .

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

>>> novo = d i c t ( a = 1 0 , b=20, c=30)


>>> p r i n t novo
{ a : 1 0 , c : 3 0 , b : 20}

70 / 180
Di ci onr i o

Percorrendo d i c i o n r i o s

>>> d = d i c t ( c = 1 0 , b=20, a=30)

>>> 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]

# loop sobre as chaves de forma ordenadas


>>> f o r key i n s o r t e d ( d . k e y s ( ) ) :
... p r i n t k e y, d [ k e y]

# r e t o r n a uma l i s t a onde cada elemento eh uma t u p l a ( c h a v e , v a l o r )


>>> p r i n t d . i t e m s ( )
[ ( a , 10), ( c , 30), ( b , 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

Como vimos podemos i t e r a r t r a b a l h a r com l i s t a s


da s e gui nte forma
>>> l i s t a = [ 2 , 4 , 6 , 8 , 1 0 ]
>>> nova = [ ]
>>> f o r x i n l i s t a :
... nova.append(x * x)

72 / 180
L i s t comprehension

Como vimos podemos i t e r a r t r a b a l h a r com l i s t a s


da s e gui nte forma
>>> l i s t a = [ 2 , 4 , 6 , 8 , 1 0 ]
>>> nova = [ ]
>>> f o r x i n l i s t a :
... nova.append(x * x)

E n t r e t a n t o a linguagem Python for ne c e uma s i n t a x e


mais compacta para r e a l i z a r esse t i p o de operao.

>>> 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

Vejamos agora como r e a l i z a r a s e gui nte operao


usando l i s t comprehension
>>> l i s t a = [ 2 , 3 , 6 , 7 , 8 , 9 , 1 0 , 1 1 ]
>>> nova = [ ]
>>> f o r x i n l i s t a :
... i f (x%2)==0:
... n o va . a p p e n d ( s t r ( x ) )
...
>>> p r i n t nova
[2, 6, 8, 10]
>>>

74 / 180
L i s t comprehension

Vejamos agora como r e a l i z a r a s e gui nte operao


usando l i s t comprehension
>>> l i s t a = [ 2 , 3 , 6 , 7 , 8 , 9 , 1 0 , 1 1 ]
>>> nova = [ ]
>>> f o r x i n l i s t a :
... i f (x%2)==0:
... n o va . a p p e n d ( s t r ( x ) )
...
>>> p r i n t nova
[2, 6, 8, 10]
>>>

Podemos r e e s c r e v e r da s e gui nte forma


>>> nova = [ s t r ( x ) f o r x i n l i s t a if(x%2==0)]

Essa nova verso i n t r o d u z uma expresso que a tua


como uma espcie de f i l t r o .
M uito mais simples e e l e g a n t e , no?

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 ) ,
...
]

L i s t a com todos a r qui vos . p y de um d i r e t r i o


>>> import os
>>> from glob import glob
>>> f i l e s = [ f f o r f i n g l o b ( * . p y ) ]
[plotPerfusionCoefs.py , fi ndS ur f. p y , . . . ]

77 / 180
Cl asses

Vamos a p r e s e n t a r de forma r p i d a como c o n s t r u i r


c l a s s e s em Python a t r a v s de alguns exemplos.
A c l a s s e mais simples do mundo
class Ponto:
pass

>>> p = P onto()
>>> p r i n t p
< main .Ponto instance a t 0x7f891f392098>

78 / 180
Cl asses

Vamos a p r e s e n t a r de forma r p i d a como c o n s t r u i r


c l a s s e s em Python a t r a v s de alguns exemplos.
A c l a s s e mais simples do mundo
class Ponto:
pass

>>> 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

Vamos c r i a r ummtodo para a l t e r a r o estado de um


Ponto
class Ponto:
# ...
def s h i f t ( s e l f , x I n c , y I n c ) :
s e l f.xC o or d += xInc
s e l f. yC o or d += yInc

82 / 180
Cl asses

Vamos c r i a r ummtodo para a l t e r a r o estado de um


Ponto
class Ponto:
# ...
def s h i f t ( s e l f , x I n c , y I n c ) :
s e l f.xC o or d += xInc
s e l f. yC o or d += yInc

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

Vamos c r i a r ummtodo para a l t e r a r o estado de um


Ponto
class Ponto:
# ...
def s h i f t ( s e l f , x I n c , y I n c ) :
s e l f.xC o or d += xInc
s e l f. yC o or d += yInc

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

def d i s t a n c e ( s e l f , other P oin t ) :


x D i f f = self .xC o or d - otherPoint .xC oor d
y D i f f = self. yC o or d - otherPoint .yC oor d
return math.sqrt( x D i f f * * 2 + yD i f f * * 2 )

85 / 180
Classes
Usando mdulos

Podemos usar a c l a s s e Ponto da s e gui nte forma


from ponto import Ponto

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

Ao c o n t r r i o da m a i o r i a das linguagens que suportam


o r i e n t a o a o b j e t o s , Python no possui um
mecanismo para esconder ou p r o t e g e r os a t r i b u t o s de
uma c l a s s e de acessos e x t e r n o s .
Em C++ temos os modi fi c a dor e s : public, private
e protected
Oresponsvel p e l a c l a s s e que deve i n d i c a r
quais a t r i b u t o s e quais mtodos devem s e r
protegidos.
E f i c a como r e s pons a bi l i da de do us u r i o da
c l a s s e , no v i o l a r essa p r o t e o .
Ainda assim p o s s v e l "emular"esse t i p o de
p r o t e o , basta a c r e s c e n t a r doi s u n d e r l i n e s na
f r e n t e do nome de um a t r i b u t o ou mtodo.

87 / 180
Classes
Escondendo a t r i b u t o s

Repare que na implementao a n t e r i o r da c l a s s e


Ponto no protegemos os a t r i b u t o s xCoord e
yCoord.
I s s o pe r mi te que umus u r i o a l t e r e os a t r i b u t o s
i n t e r n o s da c l a s s e Ponto
class Ponto:
def i n i t ( s e l f , x , y ) :
sel f.xC o or d = x
s e l f. yC o or d = y

>>> 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

Python pe r mi te emular esse ocultamento de


informao da s e gui nte
class Linha:
def i n i t ( s e l f , pA, pB ):
s e l f . pontoA = pA s e l f . # a t r i b u t o protegi do
pontoB = pB # a t r i b u t o protegi do

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 ()

Ainda assim em Python, existem formas do us u r i o


acessar os a t r i b u t o s d i r e t a m e n t e .
89 / 180
Classes
Sobrecarga de operadores

EmPython podemos implementar e d e f i n i r a


f u n c i o n a l i d a d e de di ve r s os operadores como + , * ,
== como p a r t e de nossas c l a s s e s .
class Ponto:
# ...
def eq ( s e l f , outr oP onto):
r e s u l t = self .xC oor d == outroPonto.xCoord and \
self . yC o or d == outroPonto.yCoord
return r e s ul t

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

Mais um exemplo de sobrecarga

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

A funo map recebe uma sequncia ( e x : lista) e


a p l i c a uma funo a cada umde seus elementos e
r e t o r n a uma sequncia com o r e s u l t a d o da a p l i c a o
da f u n o .
C a l c u l a r o quadrado dos elementos de uma l i s t a
>>> def square(num): r e t u r n num*num
>>> p r i n t map(square, r a n g e ( 5 ) )
[ 0 , 1 , 4 , 9 , 16]

94 / 180
Programao Funcional
map

A funo map recebe uma sequncia ( e x : lista) e


a p l i c a uma funo a cada umde seus elementos e
r e t o r n a uma sequncia com o r e s u l t a d o da a p l i c a o
da f u n o .
C a l c u l a r o quadrado dos elementos de uma l i s t a
>>> def square(num): r e t u r n num*num
>>> p r i n t map(square, r a n g e ( 5 ) )
[ 0 , 1 , 4 , 9 , 16]

Somar elemento a elemento de duas l i s t a s


>>> def s um (a,b ): r e t u r n a + b
>>> p r i n t r a n g e ( 5 )
[ 0 , 1, 2, 3, 4]
>>> p r i n t r a n g e ( 1 0 , 1 5 )
[ 1 0 , 11, 12, 13, 14]
>>> p r i n t map(sum, r a n g e ( 5 ) , r a n g e ( 1 0 , 1 5 ) )
[ 1 0 , 12, 14, 16, 18]

95 / 180
Programao Funcional
filter

A funo f i l t e r recebe ump r e d i c a t o e r e t o r n a


apenas os elementos da sequncia para os quais o
predicado r e s u l t a no v a l o r T r u e .

>>> 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

A funo reduce comea com umv a l o r i n i c i a l , e reduz


a sequncia a t umnico v a l o r a pl i c a ndo a funo em
cada umdos elementos da sequncia j u n t o com o
valor atual reduzido.
C a l c u l a r a soma dos quadrados dos nmeros de 0 a
4 de uma l i s t a

>>> def soma(reduced,num): r e t u r n reduced + num*num


>>> p r i n t reduce(soma, r a n g e ( 5 ) , 0 )
30

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

Python suporta a c r i a o de funes annimas ( i . e :


funes que no esto l i g a d a s a um nome)
em tempo de execuo, usando uma construo
a t r a v s da p a l a v r a chave lambda.
>>> def f ( x ) : r e t u r n x * * 2
>>> print f ( 8 )
64
>>>
>>> g = lambda x : x * * 2
>>> print g(8)
64

Funes lambda no precisam de usar a p a l a v r a


chave r e t u r n

99 / 180
Programao Funcional

Vejamos um exemplo mais i n t e r e s s a n t e


>>> def make _ incrementor ( n ) : r e t u r n lambda x : x + n
>>>
>>> f = make _ incrementor(2)
>>> g = make _ incrementor(6)
>>>
>>> p r i n t f ( 4 2 ) , g ( 4 2 )
44 48

100 / 180
Programao Funcional

Vejamos um exemplo mais i n t e r e s s a n t e


>>> def make _ incrementor ( n ) : r e t u r n lambda x : x + n
>>>
>>> f = make _ incrementor(2)
>>> g = make _ incrementor(6)
>>>
>>> p r i n t f ( 4 2 ) , g ( 4 2 )
44 48

Ouso de funes lambda com map, f i l t e r e reduce


muito p r t i c o
>>> p r i n t map(lambda x : x * * 2 , r a n g e ( 5 ) )
[0, 1, 4, 9 , 16]
>>> p r i n t f i l t e r ( l a m b d a x : x % 2 == 0 , r a n g e ( 5 ) )
[0,2,4]
>>> p r i n t reduce(lambda r , n : r + n * n , r a n g e ( 5 ) , 0 )
30

101 / 180
Ar qui vos

Arquivos so umt i p o b u i l t - i n do Python que so


representados por o b j e t o s .
Ou s e j a , no p r e c i s o de i m p o r t a r mdulos para
t r a b a l h a r com a r qui vos em seu programa.
Antes de um a r qui vo s e r usado p r e c i s o p r i m e i r o
c r i a r um o b j e t o que r e p r e s e n t a o a r qui vo e ento
a b r i r o mesmo.
i n f i l e = open(dados.txt, r )
outfile = open(notas.txt, w)

Depois que o processamento com os a r qui vos


t e r m i n a , p r e c i s o f e c h a r os mesmos
infile.close()
outfile.close()

102 / 180
Ar qui vos

Escrevendo em a r qui vos


outfile = open(notas.txt,w)

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

Lendo de a r qui vos


i n f i l e = open( " d a t a . t x t " , " r " )
line = infile.readline()
while l i n e ! = " " :
print( line )
line = infile.readline()
infile.close()

104 / 180
Ar qui vos

Lendo de a r qui vos


i n f i l e = open( " d a t a . t x t " , " r " )
line = infile.readline()
while l i n e ! = " " :
print( line )
line = infile.readline()
infile.close()

Podemos usar o metodo r s t r i p ( ) para remover


espacos em branco d i r e i t a
line = infile.readline()
sline = l i n e . r s t r i p ( )

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

Vamos implementar uma funo que recebe a s t r i n g


com o nome de uma r qui vo t e x t o , contendo as
coordenadas de umconjunto de pontos 2 D, l o seu
contedo e r e t o r n a uma l i s t a s com o b j e t o s P onto.
Teremos que usar a c l a s s e Ponto d e f i n i d a
anteriormente.
Exemplo:

>>> arquivo = " p o n t o s . t x t "


>>> pts = l e _ pont os ( ar qu i vo )
>>> p r i n t pts
[< main .Ponto instance a t 0x0538F3C8>,
< main .Ponto instance a t 0x0538F440>,
< main .Ponto instance a t 0x0538F260>,
< main .Ponto instance a t 0x0538F3F0>]

106 / 180
EXERC CI O

Considere a r qui vos de e ntr a da do t i p o 9


0.0 0.0
1.0 0.0
2.0 0.0
0.0 1.0
1.0 1.0
2.0 1.0
0.0 2.0
1.0 2.0
2.0 2.0

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

Gerar dados ( s i m u l a o , experimentos )


M anipular e processar os dados
V i s u a l i z a r os r e s u l t a d o s
Para entender, i n t e r p r e t a r e v a l i d a r o que
estamos fazendo
Comunicar os r e s u l t a d o s
Produz ir f i g u r a s para r e l a t r i o s e publicaes
Apresentaes
O b j e t i v o : a p r e s e n t a r os elementos bsicos da
linguagem Python para e s c r e ve r programas para
soluo computacional de problemas c i e n t f i c o s ,
m a n i p u l a r , processar e v i s u a l i z a r os dados.

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

# Python puro # NumPy


import time import time
import numpy as np
l = 10000000
l = 10000000
start = time.time()
a, b = range(l), range(l) start = time.time()
c = [] a = np.arange(l )
for i in a: b = np.arange(l )
c.append(a[ i] * b [ i ] ) c = a * b
t = time.time() - start t = time.time() - start

print(" Tem po: %s" % t ) print(" Tem po: %s" % t )

Tempo: 4.49 s Tempo: 0.37 s

112 / 180
Criando vetores NumPy

Arrays NumPy podem s e r c r i a d o s a p a r t i r de


e s t r u t u r a s de dados do Python ( l i s t a s , t u p l a s ) ou
a p a r t i r de funes e s p e c f i c a s para c r i a o de
arrays.

zeros((M ,N)) ve t o r com z e r o s , M l i n h a s , N colunas


ones((M,N)) ve t o r com uns, Ml i n h a s , N colunas
em pty( (M ,N ) ) ve t o r v a z i o , M l i n h a s , N colunas
zeros_like(A) ve t o r com z e r o s , mesmo formato de A
ones_like(A) ve t o r com uns, mesmo formato de A
empty_like(A) ve t o r v a z i o , mesmo formato de A
random.random((M,N)) ve t o r com numeros a l e a t o r i o s , MxN
identity(N) m a t r i z i d e n t i d a d e NxN, ponto f l u t u a n t e
array([[1.5,2,3],[4,5,6] ]) c r i a a p a r t i r de l i s t a ou t u p l a
arange(I, F , P) ve t o r com i n i c i o I , f i m F , passo P
l i n s p a c e ( I , F , N) ve t o r com N nmeros de I a t F

113 / 180
Criando vetores NumPy

>>> import numpy as np


>>> a = n p . a r r a y ( [ 3 6 . 4 , 2 1 . 6 , 1 5 . 6 , 2 7 . 5 ] ) # dtype = np.float64
>>> a
array([ 36.4, 21.6, 15.6, 27.5])

>>> 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 = np.ar ange(10) # dtype = n p . i n t 3 2


>>> a
ar r ay([0, 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9])

>>> 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

Exemplo com a r r a y bi di m e ns i ona l

>>> a = np.ar ange(24)


>>> a = a . r e s h a p e ( ( 4 , 6 ) )
>>> a [ 2 , 4 ]
16

116 / 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 ]
array([ 6 , 7, 8, 9 , 10, 11])

117 / 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 ]
array([ 6 , 7, 8, 9 , 10, 11])
>>> a [ - 1 ]
a r r a y([ 1 8 , 19, 20, 21, 22, 23])

118 / 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])

119 / 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]])

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

NumPy suporta operaes a r i t m t i c a s e n t r e a r r a ys


sem o uso de loops com f o r (implementado em C)

>>> import numpy as np


>>> a , b = n p . a r a n g e ( 1 , 1 1 ) , n p . a r a n g e ( 1 , 1 1 )
>>> a
array([ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10])
>>> a + 1
array([ 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10, 11])
>>> a * 2
array([ 2 , 4 , 6 , 8 , 10, 12, 14, 16, 18, 20])
>>> a * b
array([ 1 , 4 , 9 , 16, 25, 36, 49, 64, 81, 100])
>>> a * * 3
a r r a y( [ 1 , 8 , 27, 64, 125, 216, 343, 512, 729, 1000])

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

Loops em v e t o r e s NumPy def f ( x ) :


muito grandes so return e x p ( s i n ( x ) )

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])

Como v e t o r i z a r funes assim?


Usar a funo where
Uso: w here(condition, x 1 , x2)
Retorna uma r r a y do mesmo tamanho de c o n d i t i o n ,
onde o elemento i i g u a l a x 1 [ i ] se c o n d i t i o n [ i ]
T r u e , ou i g u a l a x 2 [ i ] caso c o n t r r i o ( F a l s e ) .

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 )

Para o exemplo a n t e r i o r temos

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

a.sum () soma todos elementos


a.min() menor elemento
a.max() maior elemento
a.m ean() mdia a r i t m t i c a
a.std() desvio padro
a.var() va r i n c i a
a.trace() trao
a . c o p y( ) r e t o r n a cpia
a.conjugate() complexo conjugado

>>> notas = n p . a r r a y ( [ 6 . , 7 . 5 , 8 . , 9 . 2 , 4.3])


>>> notas.mean()
7.0
>>> notas. m ax ()
9.2
>>> notas.min()
4.3

130 / 180
Copiando Arrays

A expresso =f a z com que aponte para o mesmo


a r r a y que. Logo, mudanas em tambm
i r o afetar

# sem usar o metodo copy()


>>> x = n p . a r r a y ( [ 1 . , 2 . , 3 . 5 ] )
>>> a = x
>>> a [ - 1 ] = 3 # tambem a l t e r a x [ - 1 ]
>>> x
ar r ay([1., 2 . , 3 . ] )

# usando o metodo copy()


>>> x = n p . a r r a y ( [ 1 . , 2 . , 3 . 5 ] )
>>> a = x . c o p y ( )
>>> a [ - 1 ] = 9
>>> a
array([ 1 . , 2 . , 9.])
>>> x
array([ 1 . , 2. , 3.5])

131 / 180
Mat r i zes

Os a r r a ys usados a t ento so do t i p o ndarray


NumPy tambm possui umt i p o chamado m a t r i x Sempre
bi di me ns i ona l
Algumas propriedades e s p e c i a i s de m a t r i z e s :
matrix.I (inversa)
matrix.T (transposta)
matrix.H (conjugada)
matrix.A (converte para a r r a y)
Operador de m u l t i p l i c a o ( * ) e f e t u a as
operaes usuais da lgebra L i n e a r
mat r i z- mat r i z
matriz-vetor
vetor-matriz

132 / 180
Mat r i zes

>>> b # vetor linha


matrix([[2, 1 ] ] )
>>> import numpy as np
>>> m = n p . m a t r i x ( [ [ 1 , 2 ] , [ 3 , 4 ] ] ) >>> b * m # v e t * mat
>>> m matrix([[5, 8 ] ] )
matrix([[1, 2 ] ,
[3, 4]]) >>> b = b.T # v e t o r coluna
>>> m . I >>> b
matrix([[-2. , 1. ] , ar r ay([[2],
[ 1.5, -0.5]]) [1]])
>>> m.T
matrix([[1, 3 ] , >>> m * b # mat * v e t
[2, 4]]) matrix([[ 4 ] ,
[10]])
>>> b = n p . a r r a y ( [ 2 , 1 ] )
>>> b = n p . m a t r i x ( b ) >>> m * m . I # mat * mat
matrix([[1.0000e+ 00, 1.1102e-16] ,
[0.0000e+ 0 0 , 1.0000e+ 00] ] )

133 / 180
Mat r i zes e lgebra Linear

>>> import numpy. l i na l g as l i n a l g

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

operaes para >>> f _ 1 , F = f . d e r i v ( ) , f.integ()


derivar, integrar >>> p r i n t f _ 1
e avaliar o
8 x + 2
polinmio
>>> p r i n t F
Exemplo: 3 2
() = + 1.333 x + 1 x - 1 x

135 / 180
Ajuste de Curvas

Dado os v a l o r e s de uma funo () em um conjunto


de pontos , e nc ontr a r uma funo
() que melhor se aproxime de () .
Aproximao p o l i n o m i a l pe l o mtodo dos mnimos
quadrados
() combinao de funes p o l i n o m i a i s

numpy.po l yf it( x, y, deg ree )

0.0 1.0 2.0 3.0 4.0 5.0


() 0.0 0.8 0.9 0.1 -0.8 -1.0

136 / 180
Ajuste de Curvas

>>> import numpy as np

>>> 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 ] )

>>> p1 = np.pol y1d ( c1 )


>>> c3 = n p . p o l y f i t ( x , y , 3 )
>>> c3
a r r a y ( [ 0.08703704, - 0 . 8 1 3 4 9 2 0 6 ,
1.69312169, - 0 . 0 3 9 6 8 2 5 4 ] )

>>> p1 = np.pol y1d ( c3 )

137 / 180
Sci Py

Coleo de a l g o r i t m o s matemticos e funes


utilitrias
Implementado em cima do NumPy
D i v i d i d o em sub-mdulos
constants: Constantes f s i c a s
f f t p a c k : Transformada Rpida de F o u r i e r
i n t e g r a t e : Integrao numrica e ODE solvers
i n t e r p o l a t e : I n t e r po lao ( S p l i n e s )
s t a t s : D i s t r i b u i e s e funes e s t a t s t i c a s
o p t i m i z e : Otimizao
sparse: Matrizes esparsas
l i n a l g : lgebra Linear
i o : Entrada e Sada
s i g n a l : Processamendo d i g i t a l de s i n a i s
ndimage: Processamento d i g i t a l de imagens

138 / 180
Integrao Numrica com SciPy
?
Exemplo:

>>> from scipy import i n t e g r a t e


>>> def f x 2 ( x ) :
>>> return x*x

>>> 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

i n t e g r a t e . q u a d usa ummtodo de quadratura


a d a p t a t i v a implementado em F o r t r a n no pacote
QUADPACK

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)

>>> import scipy


>>> from scipy import ndimage
>>> from pylab import * # b i b l i o t e c a m a t p l o t l i b - proximo t o p i c o !
>>> lena = s c i p y . l e n a ( )

>>> 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)

>>> imshow(lena, cmap=cm.gray)


>>> show()

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

# c r i a uma versao com r uido

>>> noisy _ lena = np.cop y( le n a )


>>> noisy _ lena += lena.st d ( ) * 0 . 5 * np .r a nd om . s ta n dar d _ n or m a l ( l e na . s ha pe )

# aplica f i l t r o s

>>> blur r ed _ le n a = n d i m a g e . g a u s s i a n _ f i l t e r ( n o i s y _ l e n a , sigma=3)


>>> median _ lena = n d i m a g e . m e d i a n _ f i l t e r ( b l u r r e d _ l e n a , s i z e = 5 )
>>> import s c i p y . s i g n a l # modulo de processamento d i g i t a l de s i n a i s
>>> wiener _ lena = s c i p y . s i g n a l . w i e n e r ( b l u r r e d _ l e n a , ( 5 , 5 ) )

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

Exemplo mais simples de uso: plot(x,y)


G r f i c o s so gerados sucessivamente, i . e . , cada
chamada a funo p l o t a l t e r a o g r f i c o

>>> from pylab import *

>>> 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

>>> from pylab import *

>>> 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

Adicionando mais informao ao g r f i c o


Legenda
Contr ol e sobre os e i x o s

>>> from pylab import *

>>> 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 (,)

>>> from pylab import *


>>> y = random.randn(1000)
>>> h i s t ( y, b i n s = 5 0 )

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

>>> from pylab import *

>>> 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

>>> from pylab import *


>>> x = linspace(-3,3,1000)
>>> y = sin(1/x)
>>> plot(x,y)

>>> savefig( " seno1sx.p ng" )

>>> s a ve f i g ( " s e n o 1 s x . p d f " )

>>> savefig ( " s e no 1s x" , format=" eps" )

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

mat pl ot l i b. sour cef or ge. net

154 / 180
Exemplo Completo

Problema: Resolver uma Equao D i f e r e n c i a l


O r d i n r i a (EDO)
Encontrar ( ) t a l que

?( ) =(( ), )

dada a condio I n i c i a l

()=

Exemplo: Crescimento exponencial (popul a o)

?( ) =

onde uma constante dada que r e p r e s e n t a a


t a x a de crescimento de u .

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
= , =,. . . ,

Soluo a n a l t i c a para o exemplo

( ) =

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

?( ) =, =, =

from pylab import * # loop no tempo


f o r k i n range(n):
# parametros u[k+1] = u[k] + dt * u[ k ]
u0 = 1 t[k+1] = t [ k ] + dt
T = 3.0
dt = 0.1 # c a l c u l a solucao e x a t a : u ( t ) = u0 e x p ( a t )
n = int(T/dt) v = u0 * e x p ( t )

# 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.

from pylab import *


from s c i p y. i n t e g r a t e import odeint

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

http://w w w.riverbankcomputing.co.uk/softw are/pyqt/

Bindings Python para o framework Qt da Nokia


Permite o desenvolvimento de a p l i c a e s com
i n t e r f a c e g r f i c a com o u s u r i o .
Multiplataforma

166 / 180
Databases

PyGreSQL (P os tgr e S QL): h t t p : / / w w w . p y g r e s q l . o r g /


psycopg (P os tgr e S QL): h t t p : / / i n i t d . o r g / p s y c o p g /
sqlite3 (SQLite):
http://docs.python.org/library/sqlite3.html
import s q l i t e 3
conn = s q l i t e 3 . c o n n e c t ( e x a m p l e . d b )

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)" )

# Save (commit) the changes


conn.commit()

# We can also close the cursor i f we ar e done with it


c.close()
167 / 180
Mechani ze

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 /

Web browsing com Python


Permite:
A b r i r qualquer URL
Preencher formulrios HTML
Visualizar histrico
e t c , e t c , etc
import r e
import mechanize

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 .

>>> from sympy import * >>> x = Symbol("x")


>>> x = S ym b o l ( x ) >>> l i m i t ( s i n ( x ) / x , x , 0 )
>>> f = 2 * c o s ( x ) 1
>>> d i f f ( f , x ) >>> l i m i t ( 1 / x , x , oo)
-2*sin(x) 0

170 / 180
Sage

Softw are matemtico l i v r e com l i e n c a GPL.


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 .
R e - u t i l i z a pacotes como Maxima, GAP, P a r i / G P ,
s oftw ar e s de r e nde r i z a o de imagens e o u t r o s .
D i s p o n v e l para uso o n l i n e v i a br ow s e r .

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

Hans P e t t e r Langtangen - "A Primer on S c i e n t i f i c


Computing w i t h Python"

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

Potrebbero piacerti anche