diff options
author | Raymond Hettinger <python@rcn.com> | 2015-05-30 05:14:07 (GMT) |
---|---|---|
committer | Raymond Hettinger <python@rcn.com> | 2015-05-30 05:14:07 (GMT) |
commit | 4c97a62ae34a0e892755a8f95ae6e11881d6feb3 (patch) | |
tree | 2e1c65ed65c929a6341884b50d74067e90d7a641 /Lib/collections/__init__.py | |
parent | 3d1151d2c000e22a90038d8fb4d77cf22430bcab (diff) | |
download | cpython-4c97a62ae34a0e892755a8f95ae6e11881d6feb3.zip cpython-4c97a62ae34a0e892755a8f95ae6e11881d6feb3.tar.gz cpython-4c97a62ae34a0e892755a8f95ae6e11881d6feb3.tar.bz2 |
Issue #23509: Speed up Counter operators
(Based on patch by Serhiy Storchaka.)
Diffstat (limited to 'Lib/collections/__init__.py')
-rw-r--r-- | Lib/collections/__init__.py | 12 |
1 files changed, 10 insertions, 2 deletions
diff --git a/Lib/collections/__init__.py b/Lib/collections/__init__.py index 6794de1..80dc4f6 100644 --- a/Lib/collections/__init__.py +++ b/Lib/collections/__init__.py @@ -753,14 +753,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''' |