From: Raymond Hettinger Date: Sat, 30 May 2015 05:14:07 +0000 (-0700) Subject: Issue #23509: Speed up Counter operators X-Git-Tag: v3.5.0b2~19 X-Git-Url: https://granicus.if.org/sourcecode?a=commitdiff_plain;h=4c97a62ae34a0e892755a8f95ae6e11881d6feb3;p=python Issue #23509: Speed up Counter operators (Based on patch by Serhiy Storchaka.) --- diff --git a/Lib/collections/__init__.py b/Lib/collections/__init__.py index 6794de1f8e..80dc4f6d4e 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'''