]> granicus.if.org Git - python/commitdiff
Issue #23509: Speed up Counter operators
authorRaymond Hettinger <python@rcn.com>
Tue, 26 May 2015 17:35:15 +0000 (10:35 -0700)
committerRaymond Hettinger <python@rcn.com>
Tue, 26 May 2015 17:35:15 +0000 (10:35 -0700)
(Based on patch by Serhiy Storchaka.)

Lib/collections/__init__.py

index fc60e13daad034ecd33e667e2bfdb444a7d09007..9c22d86d798036af6f71d7a9c521ab16738f3314 100644 (file)
@@ -736,14 +736,22 @@ class Counter(dict):
 
     def __pos__(self):
         'Adds an empty counter, effectively stripping negative and zero counts'
-        return self + Counter()
+        result = Counter()
+        for elem, count in self.items():
+            if count > 0:
+                result[elem] = count
+        return result
 
     def __neg__(self):
         '''Subtracts from an empty counter.  Strips positive and zero counts,
         and flips the sign on negative counts.
 
         '''
-        return Counter() - self
+        result = Counter()
+        for elem, count in self.items():
+            if count < 0:
+                result[elem] = 0 - count
+        return result
 
     def _keep_positive(self):
         '''Internal method to strip elements with a negative or zero count'''