diff options
author | Raymond Hettinger <python@rcn.com> | 2009-01-21 20:36:27 (GMT) |
---|---|---|
committer | Raymond Hettinger <python@rcn.com> | 2009-01-21 20:36:27 (GMT) |
commit | e0d1b9f11fc10cc2fb797606dc55967a66821529 (patch) | |
tree | 2a8ae4cab2ea1614a2ef2f7f3c6557b08862fd20 /Lib | |
parent | 63b3a97a2a7277fb05e2aeaee9890a25fb385702 (diff) | |
download | cpython-e0d1b9f11fc10cc2fb797606dc55967a66821529.zip cpython-e0d1b9f11fc10cc2fb797606dc55967a66821529.tar.gz cpython-e0d1b9f11fc10cc2fb797606dc55967a66821529.tar.bz2 |
Simplify explanation of multiset operations by removing restrictions on negative inputs.
Diffstat (limited to 'Lib')
-rw-r--r-- | Lib/collections.py | 4 | ||||
-rw-r--r-- | Lib/test/test_collections.py | 17 |
2 files changed, 11 insertions, 10 deletions
diff --git a/Lib/collections.py b/Lib/collections.py index 45558f9..232c772 100644 --- a/Lib/collections.py +++ b/Lib/collections.py @@ -314,8 +314,8 @@ class Counter(dict): if not isinstance(other, Counter): return NotImplemented result = Counter() - for elem, count in self.items(): - newcount = count - other[elem] + for elem in set(self) | set(other): + newcount = self[elem] - other[elem] if newcount > 0: result[elem] = newcount return result diff --git a/Lib/test/test_collections.py b/Lib/test/test_collections.py index 6630c4e..7195634 100644 --- a/Lib/test/test_collections.py +++ b/Lib/test/test_collections.py @@ -462,18 +462,19 @@ class TestCounter(unittest.TestCase): for i in range(1000): # test random pairs of multisets p = Counter(dict((elem, randrange(-2,4)) for elem in elements)) + p.update(e=1, f=-1, g=0) q = Counter(dict((elem, randrange(-2,4)) for elem in elements)) - for counterop, numberop, defneg in [ - (Counter.__add__, lambda x, y: x+y if x+y>0 else 0, True), - (Counter.__sub__, lambda x, y: x-y if x-y>0 else 0, False), - (Counter.__or__, max, False), - (Counter.__and__, min, False), + q.update(h=1, i=-1, j=0) + for counterop, numberop in [ + (Counter.__add__, lambda x, y: max(0, x+y)), + (Counter.__sub__, lambda x, y: max(0, x-y)), + (Counter.__or__, lambda x, y: max(0,x,y)), + (Counter.__and__, lambda x, y: max(0, min(x,y))), ]: result = counterop(p, q) for x in elements: - # all except __add__ are undefined for negative inputs - if defneg or (p[x] >= 0 and q[x] >= 0): - self.assertEqual(numberop(p[x], q[x]), result[x]) + self.assertEqual(numberop(p[x], q[x]), result[x], + (counterop, x, p, q)) # verify that results exclude non-positive counts self.assert_(x>0 for x in result.values()) |