[Python-checkins] cpython: Issue #23509: Speed up Counter operators

raymond.hettinger python-checkins at python.org
Tue May 26 19:35:23 CEST 2015


https://hg.python.org/cpython/rev/5780ee2c18e1
changeset:   96303:5780ee2c18e1
user:        Raymond Hettinger <python at rcn.com>
date:        Tue May 26 10:35:15 2015 -0700
summary:
  Issue #23509: Speed up Counter operators
(Based on patch by Serhiy Storchaka.)

files:
  Lib/collections/__init__.py |  12 ++++++++++--
  1 files changed, 10 insertions(+), 2 deletions(-)


diff --git a/Lib/collections/__init__.py b/Lib/collections/__init__.py
--- a/Lib/collections/__init__.py
+++ b/Lib/collections/__init__.py
@@ -736,14 +736,22 @@
 
     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'''

-- 
Repository URL: https://hg.python.org/cpython


More information about the Python-checkins mailing list