update from Atlas
This commit is contained in:
19
11-iface-abc/bingo.py
Normal file
19
11-iface-abc/bingo.py
Normal file
@@ -0,0 +1,19 @@
|
||||
import random
|
||||
|
||||
from tombola import Tombola
|
||||
|
||||
|
||||
class BingoCage(Tombola): # <1>
|
||||
|
||||
def __init__(self, items):
|
||||
self._balls = list(items) # <2>
|
||||
|
||||
def load(self, items):
|
||||
self._balls.extend(items)
|
||||
|
||||
def pick(self):
|
||||
try:
|
||||
position = random.randrange(len(self._balls)) # <3>
|
||||
except ValueError:
|
||||
raise LookupError('pop from empty BingoCage')
|
||||
return self._balls.pop(position) # <4>
|
||||
26
11-iface-abc/frenchdeck2.py
Normal file
26
11-iface-abc/frenchdeck2.py
Normal file
@@ -0,0 +1,26 @@
|
||||
import collections
|
||||
|
||||
Card = collections.namedtuple('Card', ['rank', 'suit'])
|
||||
|
||||
class FrenchDeck2(collections.MutableSequence):
|
||||
ranks = [str(n) for n in range(2, 11)] + list('JQKA')
|
||||
suits = 'spades diamonds clubs hearts'.split()
|
||||
|
||||
def __init__(self):
|
||||
self._cards = [Card(rank, suit) for suit in self.suits
|
||||
for rank in self.ranks]
|
||||
|
||||
def __len__(self):
|
||||
return len(self._cards)
|
||||
|
||||
def __getitem__(self, position):
|
||||
return self._cards[position]
|
||||
|
||||
def __setitem__(self, position, value): # <1>
|
||||
self._cards[position] = value
|
||||
|
||||
def __delitem__(self, position): # <2>
|
||||
del self._cards[position]
|
||||
|
||||
def insert(self, position, value): # <3>
|
||||
self._cards.insert(position, value)
|
||||
24
11-iface-abc/lotto.py
Normal file
24
11-iface-abc/lotto.py
Normal file
@@ -0,0 +1,24 @@
|
||||
import random
|
||||
|
||||
from tombola import Tombola
|
||||
|
||||
|
||||
class LotteryBlower(Tombola):
|
||||
|
||||
def __init__(self, iterable):
|
||||
self.randomizer = random.SystemRandom() # <1>
|
||||
self.clear()
|
||||
self.load(iterable)
|
||||
|
||||
def clear(self):
|
||||
self._balls = []
|
||||
|
||||
def load(self, iterable):
|
||||
self._balls.extend(iterable)
|
||||
self.randomizer.shuffle(self._balls) # <2>
|
||||
|
||||
def pick(self):
|
||||
return self._balls.pop() # <3>
|
||||
|
||||
def loaded(self): # <4>
|
||||
return len(self._balls) > 0
|
||||
23
11-iface-abc/tombola.py
Normal file
23
11-iface-abc/tombola.py
Normal file
@@ -0,0 +1,23 @@
|
||||
import abc
|
||||
|
||||
class Tombola(abc.ABC): # <1>
|
||||
|
||||
@abc.abstractmethod
|
||||
def load(self, iterable): # <2>
|
||||
"""Add items from an iterable."""
|
||||
|
||||
@abc.abstractmethod
|
||||
def pick(self): # <3>
|
||||
"""Remove item at random, returning it.
|
||||
|
||||
This method should raise `LookupError` when the instance is empty.
|
||||
"""
|
||||
|
||||
def loaded(self): # <4>
|
||||
try:
|
||||
item = self.pick()
|
||||
except LookupError:
|
||||
return False
|
||||
else:
|
||||
self.load([item]) # put it back
|
||||
return True
|
||||
36
11-iface-abc/tombola_runner.py
Normal file
36
11-iface-abc/tombola_runner.py
Normal file
@@ -0,0 +1,36 @@
|
||||
# BEGIN TOMBOLA_RUNNER
|
||||
import doctest
|
||||
|
||||
from tombola import Tombola
|
||||
|
||||
# modules to test
|
||||
import bingo, lotto, tombolist, drum # <1>
|
||||
|
||||
TEST_FILE = 'tombola_tests.rst'
|
||||
TEST_MSG = '{0:16} {1.attempted:2} tests, {1.failed:2} failed - {2}'
|
||||
|
||||
|
||||
def main(argv):
|
||||
verbose = '-v' in argv
|
||||
real_subclasses = Tombola.__subclasses__() # <2>
|
||||
virtual_subclasses = list(Tombola._abc_registry) # <3>
|
||||
|
||||
for cls in real_subclasses + virtual_subclasses: # <4>
|
||||
test(cls, verbose)
|
||||
|
||||
|
||||
def test(cls, verbose=False):
|
||||
|
||||
res = doctest.testfile(
|
||||
TEST_FILE,
|
||||
globs={'ConcreteTombola': cls}, # <5>
|
||||
verbose=verbose,
|
||||
optionflags=doctest.REPORT_ONLY_FIRST_FAILURE)
|
||||
tag = 'FAIL' if res.failed else 'OK'
|
||||
print(TEST_MSG.format(cls.__name__, res, tag)) # <6>
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
import sys
|
||||
main(sys.argv)
|
||||
# END TOMBOLA_RUNNER
|
||||
64
11-iface-abc/tombola_subhook.py
Normal file
64
11-iface-abc/tombola_subhook.py
Normal file
@@ -0,0 +1,64 @@
|
||||
"""
|
||||
Variation of ``tombola.Tombola`` implementing ``__subclasshook__``.
|
||||
|
||||
Tests with simple classes::
|
||||
|
||||
>>> Tombola.__subclasshook__(object)
|
||||
NotImplemented
|
||||
>>> class Complete:
|
||||
... def __init__(): pass
|
||||
... def load(): pass
|
||||
... def pick(): pass
|
||||
... def loaded(): pass
|
||||
...
|
||||
>>> Tombola.__subclasshook__(Complete)
|
||||
True
|
||||
>>> issubclass(Complete, Tombola)
|
||||
|
||||
"""
|
||||
|
||||
|
||||
from abc import ABC, abstractmethod
|
||||
from inspect import getmembers, isfunction
|
||||
|
||||
|
||||
class Tombola(ABC): # <1>
|
||||
|
||||
@abstractmethod
|
||||
def __init__(self, iterable): # <2>
|
||||
"""New instance is loaded from an iterable."""
|
||||
|
||||
@abstractmethod
|
||||
def load(self, iterable):
|
||||
"""Add items from an iterable."""
|
||||
|
||||
@abstractmethod
|
||||
def pick(self): # <3>
|
||||
"""Remove item at random, returning it.
|
||||
|
||||
This method should raise `LookupError` when the instance is empty.
|
||||
"""
|
||||
|
||||
def loaded(self): # <4>
|
||||
try:
|
||||
item = self.pick()
|
||||
except LookupError:
|
||||
return False
|
||||
else:
|
||||
self.load([item]) # put it back
|
||||
return True
|
||||
|
||||
@classmethod
|
||||
def __subclasshook__(cls, other_cls):
|
||||
if cls is Tombola:
|
||||
interface_names = function_names(cls)
|
||||
found_names = set()
|
||||
for a_cls in other_cls.__mro__:
|
||||
found_names |= function_names(a_cls)
|
||||
if found_names >= interface_names:
|
||||
return True
|
||||
return NotImplemented
|
||||
|
||||
|
||||
def function_names(obj):
|
||||
return {name for name, _ in getmembers(obj, isfunction)}
|
||||
80
11-iface-abc/tombola_tests.rst
Normal file
80
11-iface-abc/tombola_tests.rst
Normal file
@@ -0,0 +1,80 @@
|
||||
==============
|
||||
Tombola tests
|
||||
==============
|
||||
|
||||
Every concrete subclass of Tombola should pass these tests.
|
||||
|
||||
|
||||
Create and load instance from iterable::
|
||||
|
||||
>>> balls = list(range(3))
|
||||
>>> globe = ConcreteTombola(balls)
|
||||
>>> globe.loaded()
|
||||
True
|
||||
|
||||
|
||||
Pick and collect balls::
|
||||
|
||||
>>> picks = []
|
||||
>>> picks.append(globe.pick())
|
||||
>>> picks.append(globe.pick())
|
||||
>>> picks.append(globe.pick())
|
||||
|
||||
|
||||
Check state and results::
|
||||
|
||||
>>> globe.loaded()
|
||||
False
|
||||
>>> sorted(picks) == balls
|
||||
True
|
||||
|
||||
|
||||
Reload::
|
||||
|
||||
>>> globe.load(balls)
|
||||
>>> globe.loaded()
|
||||
True
|
||||
>>> picks = [globe.pick() for i in balls]
|
||||
>>> globe.loaded()
|
||||
False
|
||||
|
||||
|
||||
Check that `LookupError` (or a subclass) is the exception
|
||||
thrown when the device is empty::
|
||||
|
||||
>>> globe = ConcreteTombola([])
|
||||
>>> try:
|
||||
... globe.pick()
|
||||
... except LookupError as exc:
|
||||
... print('OK')
|
||||
OK
|
||||
|
||||
|
||||
Load and pick 100 balls to verify that they all come out::
|
||||
|
||||
>>> balls = list(range(100))
|
||||
>>> globe = ConcreteTombola(balls)
|
||||
>>> picks = []
|
||||
>>> while globe.loaded():
|
||||
... picks.append(globe.pick())
|
||||
>>> len(picks) == len(balls)
|
||||
True
|
||||
>>> set(picks) == set(balls)
|
||||
True
|
||||
|
||||
|
||||
Check that the order has changed and is not simply reversed::
|
||||
|
||||
>>> picks != balls
|
||||
True
|
||||
>>> picks[::-1] != balls
|
||||
True
|
||||
|
||||
Note: the previous 2 tests have a *very* small chance of failing
|
||||
even if the implementation is OK. The probability of the 100
|
||||
balls coming out, by chance, in the order they were loaded is
|
||||
1/100!, or approximately 1.07e-158. It's much easier to win the
|
||||
Lotto or to become a billionaire working as a programmer.
|
||||
|
||||
THE END
|
||||
|
||||
19
11-iface-abc/tombolist.py
Normal file
19
11-iface-abc/tombolist.py
Normal file
@@ -0,0 +1,19 @@
|
||||
from random import randrange
|
||||
|
||||
from tombola import Tombola
|
||||
|
||||
@Tombola.register # <1>
|
||||
class TomboList(list): # <2>
|
||||
|
||||
def pick(self):
|
||||
if self: # <3>
|
||||
position = randrange(len(self))
|
||||
return self.pop(position) # <4>
|
||||
else:
|
||||
raise LookupError('pop from empty TomboList')
|
||||
|
||||
def load(self, iterable): self.extend(iterable) # <5>
|
||||
|
||||
def loaded(self): return bool(self) # <6>
|
||||
|
||||
# Tombola.register(TomboList) # <- Python 3.2 or earlier
|
||||
Reference in New Issue
Block a user