summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorRaymond Hettinger <python@rcn.com>2015-05-26 17:35:15 (GMT)
committerRaymond Hettinger <python@rcn.com>2015-05-26 17:35:15 (GMT)
commit944db38cb720b511aad5d7850dec71402e7e2725 (patch)
tree770ee56b5039b95fa7689eb542e1aee8b8817c0f
parent06f155f4884dff99bfd72a38d8930449a24cbf28 (diff)
downloadcpython-944db38cb720b511aad5d7850dec71402e7e2725.zip
cpython-944db38cb720b511aad5d7850dec71402e7e2725.tar.gz
cpython-944db38cb720b511aad5d7850dec71402e7e2725.tar.bz2
Issue #23509: Speed up Counter operators
(Based on patch by Serhiy Storchaka.)
-rw-r--r--Lib/collections/__init__.py12
1 files changed, 10 insertions, 2 deletions
diff --git a/Lib/collections/__init__.py b/Lib/collections/__init__.py
index fc60e13..9c22d86 100644
--- a/Lib/collections/__init__.py
+++ b/Lib/collections/__init__.py
@@ -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'''