Last active
August 29, 2015 13:58
-
-
Save ramalho/10207773 to your computer and use it in GitHub Desktop.
Solução do Theo Alves
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 carregar(self, seq): | |
| self.itens = list(seq) | |
| def misturar(self, misturadora=None): | |
| if misturadora: # LR: isso funciona mas é melhor sempre testar explicitamente argumento is None | |
| misturadora(self.itens) | |
| else: | |
| shuffle(self.itens) | |
| def sortear(self): | |
| return self.itens.pop() | |
| def carregada(self): | |
| return bool(self.itens) | |
| def __iter__(self): | |
| while self.itens: | |
| yield self.sortear() |
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
| # coding: utf-8 | |
| """ | |
| =========================== | |
| Testando um tômbola com bug | |
| =========================== | |
| Para começar, vamos criar uma instância de tômbola. Nessa implementação, | |
| é necessário fornecer uma sequência de itens ao construtor:: | |
| >>> from tombola_bug import Tombola | |
| >>> bolas = [77, 88, 99] | |
| >>> t = Tombola(bolas) | |
| >>> t.carregada() | |
| True | |
| Vamos tirar a última bola:: | |
| >>> t.sortear() # sortear sem misturar devolve o ultimo item colocado | |
| 99 | |
| Agora veja o que aconteceu com a lista ``bolas``:: | |
| >>> bolas #doctest: +SKIP | |
| [77, 88] | |
| (veja nota no final deste texto para enteder o -SKIP) | |
| Porque isso aconteceu? | |
| Dica: a explicação começa por aqui:: | |
| >>> t.itens is bolas | |
| True | |
| Isso é um problema porque o usuário da tômbola provavelmente não espera | |
| que itens de sua lista serão descartados durante o uso. | |
| O que deve ser feito para eliminar este problema e fazer o teste a seguir | |
| passar? | |
| >>> bolas | |
| [77, 88, 99] | |
| NOTA: Uma vez resolvido este exercício você poderá mudar a diretiva -SKIP | |
| para +SKIP na linha 24 para ignorar aquele teste. | |
| """ | |
| class Tombola(object): | |
| '''IMPLEMENTACAO COM BUG!!!''' # LR: consertado pelo Theo Alves | |
| def __init__(self, seq): | |
| self.itens = seq | |
| self.__itens = list(seq) # LR: sim, era isso mesmo! | |
| def carregar(self, seq): | |
| self.__itens.extend(seq) | |
| def sortear(self): | |
| return self.__itens.pop() | |
| def carregada(self): | |
| return bool(self.__itens) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment