@@ -495,10 +495,13 @@ def __add__(self, other):
495495 if not isinstance (other , Counter ):
496496 return NotImplemented
497497 result = Counter ()
498- for elem in set ( self ) | set ( other ):
499- newcount = self [ elem ] + other [elem ]
498+ for elem , count in self . items ( ):
499+ newcount = count + other [elem ]
500500 if newcount > 0 :
501501 result [elem ] = newcount
502+ for elem , count in other .items ():
503+ if elem not in self and count > 0 :
504+ result [elem ] = count
502505 return result
503506
504507 def __sub__ (self , other ):
@@ -511,10 +514,13 @@ def __sub__(self, other):
511514 if not isinstance (other , Counter ):
512515 return NotImplemented
513516 result = Counter ()
514- for elem in set ( self ) | set ( other ):
515- newcount = self [ elem ] - other [elem ]
517+ for elem , count in self . items ( ):
518+ newcount = count - other [elem ]
516519 if newcount > 0 :
517520 result [elem ] = newcount
521+ for elem , count in other .items ():
522+ if elem not in self and count < 0 :
523+ result [elem ] = 0 - count
518524 return result
519525
520526 def __or__ (self , other ):
@@ -527,11 +533,14 @@ def __or__(self, other):
527533 if not isinstance (other , Counter ):
528534 return NotImplemented
529535 result = Counter ()
530- for elem in set ( self ) | set ( other ):
531- p , q = self [ elem ], other [elem ]
532- newcount = q if p < q else p
536+ for elem , count in self . items ( ):
537+ other_count = other [elem ]
538+ newcount = other_count if count < other_count else count
533539 if newcount > 0 :
534540 result [elem ] = newcount
541+ for elem , count in other .items ():
542+ if elem not in self and count > 0 :
543+ result [elem ] = count
535544 return result
536545
537546 def __and__ (self , other ):
@@ -544,11 +553,9 @@ def __and__(self, other):
544553 if not isinstance (other , Counter ):
545554 return NotImplemented
546555 result = Counter ()
547- if len (self ) < len (other ):
548- self , other = other , self
549- for elem in filter (self .__contains__ , other ):
550- p , q = self [elem ], other [elem ]
551- newcount = p if p < q else q
556+ for elem , count in self .items ():
557+ other_count = other [elem ]
558+ newcount = count if count < other_count else other_count
552559 if newcount > 0 :
553560 result [elem ] = newcount
554561 return result
0 commit comments