mirror of
https://github.com/python/cpython.git
synced 2025-09-27 10:50:04 +00:00
Issue #23509: Speed up Counter operators
(Based on patch by Serhiy Storchaka.)
This commit is contained in:
parent
06f155f488
commit
944db38cb7
1 changed files with 10 additions and 2 deletions
|
@ -736,14 +736,22 @@ class Counter(dict):
|
||||||
|
|
||||||
def __pos__(self):
|
def __pos__(self):
|
||||||
'Adds an empty counter, effectively stripping negative and zero counts'
|
'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):
|
def __neg__(self):
|
||||||
'''Subtracts from an empty counter. Strips positive and zero counts,
|
'''Subtracts from an empty counter. Strips positive and zero counts,
|
||||||
and flips the sign on negative 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):
|
def _keep_positive(self):
|
||||||
'''Internal method to strip elements with a negative or zero count'''
|
'''Internal method to strip elements with a negative or zero count'''
|
||||||
|
|
Loading…
Add table
Add a link
Reference in a new issue