Created
October 5, 2012 21:17
-
-
Save mercutio22/3842478 to your computer and use it in GitHub Desktop.
exercicios da aulas 2 objetos pythonicos (atrasado)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
====================== | |
Lista 2: Questão bônus | |
====================== | |
Esta é uma questão avançada, não se sinta mal se não tiver tempo para | |
resolvê-la. | |
Considere uma mesma instância de tômbola iterável (como implementada no | |
exerício 2.2). Se tal tômbola for utilizada em dois laços ``for``, as | |
iterações serão independentes ou não? | |
Em termos práticos, sua implementação apresenta este comportamento:: | |
>>> t = Tombola() | |
>>> t.carregar([1, 2, 3]) | |
>>> for i in t: | |
... print i | |
... break | |
3 | |
>>> for i in t: | |
... print i | |
2 | |
1 | |
Ou este outro comportamento? :: | |
>>> t = Tombola() | |
>>> t.carregar([1, 2, 3]) | |
>>> for i in t: | |
... print i | |
... break | |
3 | |
>>> for i in t: | |
... print i | |
3 | |
2 | |
1 | |
Resposta: Eu esperaria o primeiro comportamento porque em minha implementação | |
as voltas do laço ficam armazedas em self.indice. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from random import shuffle | |
class Tombola(object): | |
'''Sorteia itens sem repetir''' | |
def __init__(self): | |
self.indice = 0 | |
def carregar(self, seq): | |
self.itens = list(seq) | |
def misturar(self, misturadora=None): | |
if misturadora is None: | |
shuffle(self.itens) | |
else: | |
misturadora(self.itens) | |
def sortear(self): | |
return self.itens.pop() | |
def carregada(self): | |
return bool(self.itens) | |
def __iter__(self): | |
return self | |
def next(self): | |
if self.indice < len(self.itens): | |
atual = self.itens[self.indice] | |
self.indice += 1 | |
return atual | |
else: | |
raise StopIteration | |
#essa outra implementação funciona, mas o print descarrega a tômbola | |
#~ if not self.carregada(): | |
#~ raise StopIteration | |
#~ else: | |
#~ return self.sortear() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment