Permalink
Browse files

lista de exercicios 1

  • Loading branch information...
0 parents commit 233a70d264f459fcf0e9b96cf07b2fdeea186025 @tganzarolli committed Dec 11, 2011
@@ -0,0 +1,4 @@
+slides/
+videos/
+*.pyc
+.DS_Store
@@ -0,0 +1,12 @@
+from listas import homens, mulheres
+
+print dict(zip(homens,mulheres))
+print "-------"
+casais = [(h,m) for h in homens for m in mulheres]
+print len(casais)
+print casais
+print "-------"
+casais = [(h,m) for h in homens if len(h) >=4 for m in mulheres if len(m) >=4]
+print len(casais)
+print casais
+print "-------"
@@ -0,0 +1,4 @@
+#tem o ponto final e o espaco
+fox = 'The quick brown fox jumps over the lazy dog.'
+fox_letters = set(l.upper() for l in fox)
+print len(fox_letters)
@@ -0,0 +1,7 @@
+import string
+fox = 'The quick brown fox jumps over the lazy dog.'
+fox_letters = set(l.upper() for l in fox if l.isalpha())
+
+import string
+letters = set(string.ascii_uppercase)
+print fox_letters == letters
@@ -0,0 +1,13 @@
+import string
+letters = set(string.ascii_uppercase)
+
+jabuti = 'Um pequeno jabuti xereta viu dez cegonhas felizes.'
+jabuti_letras = set(l.upper() for l in jabuti if l.isalpha())
+for j in sorted(set(jabuti_letras)):
+ print j
+print len(jabuti_letras)
+
+#o que existe em A e nao existe B
+print letters - jabuti_letras
+#o que existe unicamente em A ou em B. Symmetric difference
+print letters ^ jabuti_letras
@@ -0,0 +1,8 @@
+from listas_redutoras import m,n
+
+print all(m)
+print all(n)
+print any(m)
+print any(n)
+print sum(n)
+print sum(m+n)
@@ -0,0 +1,3 @@
+from listas_redutoras import m,n
+
+print sum(a*b for (a,b) in enumerate(n))
@@ -0,0 +1,6 @@
+from listas_redutoras import m,n
+
+print zip(m, n)
+for i in (x for (x,y) in zip(m, n)):
+ print i
+print all(x for (x,y) in zip(m, n))
@@ -0,0 +1,3 @@
+from listas_redutoras import m,n
+
+print sum(x*y for (x,y) in zip(m, n))
@@ -0,0 +1,6 @@
+#antes
+>>> desempenho()
+1.20384216309
+#depois
+>>> desempenho()
+0.000383138656616
@@ -0,0 +1,53 @@
+'''
+ >>> from baralho import Baralho
+ >>> b = Baralho()
+ >>> b[0]
+ <A de copas>
+ >>> b[:3]
+ [<A de copas>, <2 de copas>, <3 de copas>]
+ >>> b[-3:]
+ [<J de paus>, <Q de paus>, <K de paus>]
+ >>> for carta in b: # doctest:+ELLIPSIS
+ ... print carta
+ <A de copas>
+ <2 de copas>
+ <3 de copas>
+ <4 de copas>
+ <5 de copas>
+ ...
+ >>> for carta in reversed(b): # doctest:+ELLIPSIS
+ ... print carta
+ <K de paus>
+ <Q de paus>
+ <J de paus>
+ <10 de paus>
+ ...
+ >>>
+
+'''
+
+
+from random import shuffle
+
+class Carta(object):
+ def __init__(self, valor, naipe):
+ self.valor = valor
+ self.naipe = naipe
+
+ def __repr__(self):
+ return '<%s de %s>' % (self.valor, self.naipe)
+
+class Baralho(object):
+ naipes = 'copas ouros espadas paus'.split()
+ valores = 'A 2 3 4 5 6 7 8 9 10 J Q K'.split()
+
+ def __init__(self):
+ self.cartas = [Carta(v, n)
+ for n in self.naipes
+ for v in self.valores]
+
+ def __getitem__(self, pos):
+ return self.cartas[pos]
+
+ def __len__(self):
+ return len(self.cartas)
@@ -0,0 +1,105 @@
+# coding: utf-8
+
+# Código testado com Python 2.7, 3.2, PyPy(1.7) 2.7 e Jython 2.5.2
+
+"""
+ >>> l = []
+ >>> busca_bin(l, 0)
+ -1
+ >>> l = [7]
+ >>> [busca_bin(l, x) for x in [0, 7, 8]]
+ [-1, 0, -1]
+ >>> l = [2, 4]
+ >>> [busca_bin(l, x) for x in l]
+ [0, 1]
+ >>> [busca_bin(l, x) for x in [1, 3, 5]]
+ [-1, -1, -1]
+ >>> l = [1, 3, 5]
+ >>> [busca_bin(l, x) for x in l]
+ [0, 1, 2]
+ >>> [busca_bin(l, x) for x in [0, 2, 4, 6]]
+ [-1, -1, -1, -1]
+ >>> l = [1, 2, 3, 4]
+ >>> [busca_bin(l, x) for x in l]
+ [0, 1, 2, 3]
+ >>> [busca_bin(l, x) for x in [0, 1.5, 4.1]]
+ [-1, -1, -1]
+
+"""
+
+try:
+ xrange
+except NameError:
+ xrange = range # para funcionar no Python 3
+
+def busca_bin(seq, item, to_insert=False):
+ """Assumindo que `seq` está ordenada, devolve a posição do `item`.
+
+ Se `item` não está presente em `seq`, devolve -1.
+ """
+ a, b = 0, len(seq)
+ i = -1
+ while (a < b):
+ i_ant = i
+ i = (a+b)//2
+ if i == i_ant:
+ break
+ atual = seq[i]
+ if item == atual:
+ return i
+ elif item < atual:
+ b = i
+ else:
+ a = i
+ if to_insert:
+ return i
+ else:
+ return -1
+
+def busca_lin_enum(seq, item):
+ for i, valor in enumerate(seq):
+ if valor == item:
+ return i
+ return -1
+
+def busca_lin_for(seq, item):
+ for i in xrange(len(seq)):
+ if seq[i] == item:
+ return i
+ return -1
+
+def busca_lin_while(seq, item):
+ i = 0
+ while i < len(seq):
+ if seq[i] == item:
+ return i
+ i += 1
+ return -1
+
+def busca_index(seq, item):
+ try:
+ return seq.index(item)
+ except ValueError:
+ return -1
+
+def desempenho():
+ import sys
+ from timeit import Timer
+ print(sys.version)
+ tam = 10**6
+ expr = '''b(l, %d), b(l, %d), b(l, %d)''' % (0, tam/2, tam)
+ for nome_busca in (k for k in sorted(globals()) if k.startswith('busca')):
+ prep = '\n'.join([
+ '''from __main__ import %s as b\n''' % nome_busca,
+ '''l = list(range(%d))''' % tam]) # Python 2 e 3: list(range(n))
+ res = min(Timer(expr, prep).repeat(number=10))
+ print('%15s: %12.8f' % (nome_busca, res))
+
+def teste():
+ import doctest
+ return doctest.testmod()[0] # devolver falhas
+
+if __name__=='__main__':
+ falhas = teste()
+ if not falhas:
+ desempenho()
@@ -0,0 +1,107 @@
+from baralho import Baralho
+
+# Classes de iteradores:
+
+# Primeira implementacao, pouco pythonica
+class InverseIter(object):
+
+ def __init__(self, cartas):
+ self.cartas=list(cartas)
+ self.cartas.reverse()
+ self.pos = -1
+
+ def next(self):
+ self.pos +=1
+ try:
+ return self.cartas[self.pos]
+ except IndexError:
+ raise StopIteration
+
+ def __iter__(self):
+ return self
+
+#Segunda, mais pythonica, ja usando expressoes geradoras
+class InverseIterGenExpr(object):
+
+ def __init__(self, cartas):
+ self.cartas=list(cartas)
+ self.cartas.reverse()
+ self.gen_expr = (carta for carta in self.cartas)
+
+ def next(self):
+ return self.gen_expr.next()
+
+ def __iter__(self):
+ return self
+
+#so com reversed
+class InverseIterGenExprPlus(object):
+
+ def __init__(self, cartas):
+ self.gen_expr = reversed(cartas)
+
+ def next(self):
+ return self.gen_expr.next()
+
+ def __iter__(self):
+ return self
+
+#Classes de baralho inverso
+
+class BaralhoInverso(Baralho):
+
+ def __init__(self, iter_class):
+ super(BaralhoInverso, self).__init__()
+ self.iter_class=iter_class
+
+ def __iter__(self):
+ return self.iter_class(self.cartas)
+
+class BaralhoInversoXPTO(BaralhoInverso):
+ pass
+
+class BaralhoInversoPlus(BaralhoInverso):
+
+ def __init__(self, iter_class):
+ super(BaralhoInversoPlus, self).__init__(iter_class)
+ self.cartas_reversas = list(self.cartas)
+ self.cartas_reversas.reverse()
+
+ def iter_genexp(self):
+ return (carta for carta in self.cartas_reversas)
+
+ def iter_object(self):
+ return self.iter_class(self.cartas_reversas)
+
+ def iter_genfun(self):
+ for carta in self.cartas_reversas:
+ yield carta
+
+b = BaralhoInversoXPTO(InverseIter) #funciona, ao contrario de Java, sem construtor explicito na subclasse :-)
+for carta in b:
+ print carta
+
+print "-----------------------------------#*#*#*#------------------------------------"
+b = BaralhoInverso(InverseIterGenExpr)
+for carta in b:
+ print carta
+
+print "-----------------------------------#*#*#*#------------------------------------"
+b = BaralhoInverso(InverseIterGenExprPlus)
+for carta in b:
+ print carta
+print "-----------------------------------#*#*#*#------------------------------------"
+b = BaralhoInversoPlus(InverseIterGenExprPlus)
+print b.iter_genexp()
+print b.iter_object()
+print b.iter_genfun()
+print "========"
+for carta in b.iter_genexp():
+ print carta
+print "========"
+for carta in b.iter_object():
+ print carta
+print "========"
+for carta in b.iter_genfun():
+ print carta
+print "========"
@@ -0,0 +1,18 @@
+from baralho import Baralho
+
+class BaralhoMisturado(Baralho):
+
+ def __iter__(self):
+ indexes = [n for n in range(len(self.cartas))]
+ from random import shuffle
+ random.shuffle(indexes)
+ for index in indexes:
+ yield self.cartas[index]
+
+b = BaralhoMisturado()
+
+for carta in b:
+ print carta
+print "-----------------------------------#*#*#*#------------------------------------"
+for carta in b:
+ print carta
@@ -0,0 +1,4 @@
+from listas import homens
+
+filtered_list = [h for h in homens if len(h) <=4]
+print filtered_list
@@ -0,0 +1,3 @@
+from listas import generate_tuple_list
+
+print generate_tuple_list()
@@ -0,0 +1,4 @@
+from listas import generate_tuple_list
+
+dict_man = dict(generate_tuple_list())
+print dict_man
@@ -0,0 +1,4 @@
+fox = 'The quick brown fox jumps over the lazy dog.'
+fox_letters = set(l.upper() for l in fox if l.isalpha())
+print len(fox_letters)
+
Oops, something went wrong.

0 comments on commit 233a70d

Please sign in to comment.