Você está na página 1de 28

Computao Cientfica em Python

Introduo ao Python

O Curso
>>> EPDFree 7.2 OR >>> Python 2.7 >>> Numpy >>> SciPy >>> Matplotlib >>> Etc.

AND
>>> Shell: DreamPie >>> Editor: PTVS - Python Tools For Visual Studio

Aplicaes e Plataformas
>>> Comercial Web e Forms >>> Games e entretenimento >>> Cientfica
>>> Windows >>> Linux >>> Mac >>> Mobile

Bibliotecas
>>> EPD Free: +100 libs: >>> Biopython computao biolgica; >>> Chaco grficos interativos; >>> Cython extenses em C; >>> GDAL anlise de dados geoespaciais; >>> Mayavi visualizao 3D; >>> Numpy processamento de arrays; >>> Pandas anlise de dados; >>> PIL processamento de imagens; >>> PyCripto criptografia; >>> SciPy matemtica, cincia e engenharia. >>> Clssicas: OpenCV, OpenGL, QT etc.

Quem usa?
>>> Google >>> Facebook >>> Twitter >>> IBM >>> Microsoft >>> Stanford, MIT et al. >>> WallDisney >>> DropBox >>> Mozilla >>> Cisco >>> Globo.Com >>> SERPRO Guido Van Rossum

Filosofia
>>> import this
>>> Hello World... >>> print 'Hello World!

>>> Case Sensitive: a <> A

Tipos e Variveis
>>> x = 1 >>> y = 1. >>> z = '1' >>> type(x) >>> type(y) >>> type(z)

Converses
>>> int(z) + x
>>> float(x) / 2 >>> str(x) * 5 >>> not bool(x)

Sequncias
>>> len(s) quantidade de itens
>>> Indexador Unidimensional: s[ inicio : fim : passo] >>> Indexador Bidimensional: s[ inicio_linha :fim_linha inicio_coluna :fim_coluna

:passo_linha, :passo_coluna]

Sequncias: Strings
>>> str = 'a.b.c.d.e.f.g.h.i.j.k.l.m.n.o.p.q.r.s.t.u.v' >>> lst = str.split('.') gera uma lista >>> chr = '_' >>> str = chr.join(lst) gera uma string
>>> str.replace('_', '.')

Sequncias: Listas, Tuplas e Dicionrios


>>> lista = ['a', 'b', 'c', 'd', 'e'] >>> lista.append('f') >>> tupla = ('a', 'b', 'c', 'd', 'e') >>> *imutvel x, y = y, x
>>> dicionario = {'a':1, 'b':2, 'c':3, 'd':4, 'e':5} >>> dicionario['f'] = 6

Linha aninhada / bidimensional


>>> lista = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [0, 0, 0]] >>> zip(*lista) transposio de lista aninhada >>> [(1, 4, 7, 0), (2, 5, 8, 0), (3, 6, 9, 0)]
>>> for i in lista: print i exibe linhas >>> for i in zip(*lista): print i exibe colunas

Mdulos
>>> from numpy import * Ruim!
>>> from numpy import abs, concatenate, sin, pi, dot, amin, amax, asarray, cov, diag, zeros, empty, exp, eye, kaiser Muito Longo! >>> import numpy Bom! >>> import numpy as np Muito Bom! >>> numpy.fft.fft() ou np.fft.fft()

Arquivos
>>> arq = open(r'v:\Vagner\teste.txt', 'a'/'w'/'r')
>>> arq.read() >>> arq.write() >>> arq.flush() >>> arq.close()

GLOB
>>> import glob as gl >>> files = gl.glob(r'c:\Temp\*.*') >>> files = gl.glob(r'c:\Temp\*.txt') >>> files = gl.glob(r'c:\Temp\*a.txt') >>> files = gl.glob(r'c:\Temp\*[a-z].txt') >>> files = gl.glob(r'c:\Temp\?a.txt') >>> import os >>> os.path.basename(files[0]) 'arquivo.txt' >>> os.path. dirname(files[0]) 'c:\Temp'

Serializao de objetos
>>> import pickle as pk
>>> file = open(r'c:\lista.pck', 'w') >>> lista = [1, 2, ..., 999999] >>> pk.dump(lista, file) >>> file.close() >>> file = open(r'c:\lista.pck', 'r') >>> lista = pk.load(file) >>> file.close()

Estruturas de deciso
>>> if variavel == 1: print 'Ol Mundo 1' elif variavel == 2 : print 'Ol Mundo 2' else: print 'Ol Mundo Qualquer... '
>>> # Indentao obrigatria!

Estruturas de repetio
>>> for i in lista: print i >>> while len(lista) > 0: print lista.pop(0)
>>> *funes range() e zip()

Controle de exceo
>>> try:
print 1/0 except: print 'Erro' finally: print 'fim!' >>> *except multiplo ZeroDivisionError, IOError, ValueError etc.

Funes
>>> def OlaMundo(): print 'Ol Mundo!' >>> def Concatenar(str1, str2): return str1 + str2
>>> OlaMundo() >>> Concatenar('Ol', 'Mundo!')

Orientao a Objetos
>>> class Classe(Pai): def __init__(self) super(self.__class__, self).__init__() self.att1 = 1 self.att2 = 'Ol mundo' def OlaMundo(self): print self.att2 @staticmethod def OlaMundoEstatico(): print 'Ol Mundo Esttico'

Classe annima: by Peter Norvig


>>> class Struct:

def __init__(self, **entries): self.__dict__.update(entries)


>>> ann = Struct( nome = 001, imagem = *0,1,...,9+ ) >>> ann.amostra 001 >>> ann.imagem [0,1,2,...,9]

Expresses Lambda
>>> lista = [[1,'b'],[2,'c'],[3,'a']]
>>> sorted(lista, key=lambda x:x[1]) >>> filter(lambda x:x[1] == 'a', lista) >>> *tipada lambda x:x.nome = 'Vagner'

Programao Funcional
>>> def f(x): return x[0] > 0 and x[0] < 3 >>> filter(f, lista)

Threads
>>> from threading import Thread as th >>> import time >>> def T1(): for i in range(0,100,2): print 'T1: ', i time.sleep(.1) >>> def T2(): for i in range(1, 100, 2): print 'T2: ', i time.sleep(.3) >>> t1 = th(target=T1) >>> t2 = th(target=T2) >>> t1.start() >>> t2.start()

Threads
>>> from threading import Thread as th >>> import time >>> def Tp(t): for i in range(0,100,2): print 'Tp: ' + str(t) + ' -', i time.sleep(t) >>> t1 = th(target=Tp, args=(.1,)) >>> t2 = th(target=Tp, args=(.3,)) >>> t1.start() >>> t2.start()

Dicas
>>> Links: >>> http://www.franciscosouza.com.br/aprendacompy/ >>> http://learnpythonthehardway.org/ >>> http://docs.python.org/index.html >>> Download: >>> EPDFree 7.2: http://enthought.com/products/epd_free.php >>> DreamPie: http://dreampie.sourceforge.net/

Exerccios
>>> Crie uma lista aninhada, com 10 registros e os seguintes atributos: nome, idade, curso e sexo. Filtre e ordene utilizando lambda;
>>> Crie uma classe para substituir a sub estrutura da lista anterior. Filtre e ordene utilizando lambda;

Você também pode gostar