Brett Cannon | 23a4a7b | 2008-05-12 00:56:28 +0000 | [diff] [blame] | 1 | __all__ = ['deque', 'defaultdict', 'namedtuple', 'UserDict', 'UserList', |
Raymond Hettinger | 4d2073a | 2009-01-20 03:41:22 +0000 | [diff] [blame] | 2 | 'UserString', 'Counter'] |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 3 | # For bootstrapping reasons, the collection ABCs are defined in _abcoll.py. |
| 4 | # They should however be considered an integral part of collections.py. |
| 5 | from _abcoll import * |
| 6 | import _abcoll |
| 7 | __all__ += _abcoll.__all__ |
| 8 | |
Christian Heimes | 99170a5 | 2007-12-19 02:07:34 +0000 | [diff] [blame] | 9 | from _collections import deque, defaultdict |
| 10 | from operator import itemgetter as _itemgetter |
| 11 | from keyword import iskeyword as _iskeyword |
| 12 | import sys as _sys |
Raymond Hettinger | b8baf63 | 2009-01-14 02:20:07 +0000 | [diff] [blame] | 13 | import heapq as _heapq |
| 14 | from itertools import repeat as _repeat, chain as _chain, starmap as _starmap |
| 15 | |
Christian Heimes | 99170a5 | 2007-12-19 02:07:34 +0000 | [diff] [blame] | 16 | |
Raymond Hettinger | 48b8b66 | 2008-02-05 01:53:00 +0000 | [diff] [blame] | 17 | ################################################################################ |
| 18 | ### namedtuple |
| 19 | ################################################################################ |
| 20 | |
Benjamin Peterson | a86f2c0 | 2009-02-10 02:41:10 +0000 | [diff] [blame^] | 21 | def namedtuple(typename, field_names, verbose=False, rename=False): |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 22 | """Returns a new subclass of tuple with named fields. |
| 23 | |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 24 | >>> Point = namedtuple('Point', 'x y') |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 25 | >>> Point.__doc__ # docstring for the new class |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 26 | 'Point(x, y)' |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 27 | >>> p = Point(11, y=22) # instantiate with positional args or keywords |
Christian Heimes | 99170a5 | 2007-12-19 02:07:34 +0000 | [diff] [blame] | 28 | >>> p[0] + p[1] # indexable like a plain tuple |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 29 | 33 |
Christian Heimes | 99170a5 | 2007-12-19 02:07:34 +0000 | [diff] [blame] | 30 | >>> x, y = p # unpack like a regular tuple |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 31 | >>> x, y |
| 32 | (11, 22) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 33 | >>> p.x + p.y # fields also accessable by name |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 34 | 33 |
Christian Heimes | 0449f63 | 2007-12-15 01:27:15 +0000 | [diff] [blame] | 35 | >>> d = p._asdict() # convert to a dictionary |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 36 | >>> d['x'] |
| 37 | 11 |
| 38 | >>> Point(**d) # convert from a dictionary |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 39 | Point(x=11, y=22) |
Christian Heimes | 0449f63 | 2007-12-15 01:27:15 +0000 | [diff] [blame] | 40 | >>> p._replace(x=100) # _replace() is like str.replace() but targets named fields |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 41 | Point(x=100, y=22) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 42 | |
| 43 | """ |
| 44 | |
Christian Heimes | 2380ac7 | 2008-01-09 00:17:24 +0000 | [diff] [blame] | 45 | # Parse and validate the field names. Validation serves two purposes, |
| 46 | # generating informative error messages and preventing template injection attacks. |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 47 | if isinstance(field_names, str): |
| 48 | field_names = field_names.replace(',', ' ').split() # names separated by whitespace and/or commas |
Benjamin Peterson | e9bbc8b | 2008-09-28 02:06:32 +0000 | [diff] [blame] | 49 | field_names = tuple(map(str, field_names)) |
Benjamin Peterson | a86f2c0 | 2009-02-10 02:41:10 +0000 | [diff] [blame^] | 50 | if rename: |
| 51 | names = list(field_names) |
| 52 | seen = set() |
| 53 | for i, name in enumerate(names): |
| 54 | if (not all(c.isalnum() or c=='_' for c in name) or _iskeyword(name) |
| 55 | or not name or name[0].isdigit() or name.startswith('_') |
| 56 | or name in seen): |
| 57 | names[i] = '_%d' % (i+1) |
| 58 | seen.add(name) |
| 59 | field_names = tuple(names) |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 60 | for name in (typename,) + field_names: |
Christian Heimes | b9eccbf | 2007-12-05 20:18:38 +0000 | [diff] [blame] | 61 | if not all(c.isalnum() or c=='_' for c in name): |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 62 | raise ValueError('Type names and field names can only contain alphanumeric characters and underscores: %r' % name) |
| 63 | if _iskeyword(name): |
| 64 | raise ValueError('Type names and field names cannot be a keyword: %r' % name) |
| 65 | if name[0].isdigit(): |
| 66 | raise ValueError('Type names and field names cannot start with a number: %r' % name) |
| 67 | seen_names = set() |
| 68 | for name in field_names: |
Benjamin Peterson | a86f2c0 | 2009-02-10 02:41:10 +0000 | [diff] [blame^] | 69 | if name.startswith('_') and not rename: |
Christian Heimes | 0449f63 | 2007-12-15 01:27:15 +0000 | [diff] [blame] | 70 | raise ValueError('Field names cannot start with an underscore: %r' % name) |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 71 | if name in seen_names: |
| 72 | raise ValueError('Encountered duplicate field name: %r' % name) |
| 73 | seen_names.add(name) |
| 74 | |
| 75 | # Create and fill-in the class template |
Christian Heimes | faf2f63 | 2008-01-06 16:59:19 +0000 | [diff] [blame] | 76 | numfields = len(field_names) |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 77 | argtxt = repr(field_names).replace("'", "")[1:-1] # tuple repr without parens or quotes |
Guido van Rossum | d59da4b | 2007-05-22 18:11:13 +0000 | [diff] [blame] | 78 | reprtxt = ', '.join('%s=%%r' % name for name in field_names) |
Christian Heimes | 99170a5 | 2007-12-19 02:07:34 +0000 | [diff] [blame] | 79 | dicttxt = ', '.join('%r: t[%d]' % (name, pos) for pos, name in enumerate(field_names)) |
Guido van Rossum | d59da4b | 2007-05-22 18:11:13 +0000 | [diff] [blame] | 80 | template = '''class %(typename)s(tuple): |
Christian Heimes | 0449f63 | 2007-12-15 01:27:15 +0000 | [diff] [blame] | 81 | '%(typename)s(%(argtxt)s)' \n |
| 82 | __slots__ = () \n |
Christian Heimes | faf2f63 | 2008-01-06 16:59:19 +0000 | [diff] [blame] | 83 | _fields = %(field_names)r \n |
Guido van Rossum | d59da4b | 2007-05-22 18:11:13 +0000 | [diff] [blame] | 84 | def __new__(cls, %(argtxt)s): |
Christian Heimes | 0449f63 | 2007-12-15 01:27:15 +0000 | [diff] [blame] | 85 | return tuple.__new__(cls, (%(argtxt)s)) \n |
Christian Heimes | faf2f63 | 2008-01-06 16:59:19 +0000 | [diff] [blame] | 86 | @classmethod |
Christian Heimes | 043d6f6 | 2008-01-07 17:19:16 +0000 | [diff] [blame] | 87 | def _make(cls, iterable, new=tuple.__new__, len=len): |
Christian Heimes | faf2f63 | 2008-01-06 16:59:19 +0000 | [diff] [blame] | 88 | 'Make a new %(typename)s object from a sequence or iterable' |
Christian Heimes | 043d6f6 | 2008-01-07 17:19:16 +0000 | [diff] [blame] | 89 | result = new(cls, iterable) |
Christian Heimes | faf2f63 | 2008-01-06 16:59:19 +0000 | [diff] [blame] | 90 | if len(result) != %(numfields)d: |
| 91 | raise TypeError('Expected %(numfields)d arguments, got %%d' %% len(result)) |
| 92 | return result \n |
Guido van Rossum | d59da4b | 2007-05-22 18:11:13 +0000 | [diff] [blame] | 93 | def __repr__(self): |
Christian Heimes | 0449f63 | 2007-12-15 01:27:15 +0000 | [diff] [blame] | 94 | return '%(typename)s(%(reprtxt)s)' %% self \n |
Christian Heimes | 99170a5 | 2007-12-19 02:07:34 +0000 | [diff] [blame] | 95 | def _asdict(t): |
Christian Heimes | 0449f63 | 2007-12-15 01:27:15 +0000 | [diff] [blame] | 96 | 'Return a new dict which maps field names to their values' |
Christian Heimes | 99170a5 | 2007-12-19 02:07:34 +0000 | [diff] [blame] | 97 | return {%(dicttxt)s} \n |
Christian Heimes | 0449f63 | 2007-12-15 01:27:15 +0000 | [diff] [blame] | 98 | def _replace(self, **kwds): |
Guido van Rossum | 3d392eb | 2007-11-16 00:35:22 +0000 | [diff] [blame] | 99 | 'Return a new %(typename)s object replacing specified fields with new values' |
Christian Heimes | faf2f63 | 2008-01-06 16:59:19 +0000 | [diff] [blame] | 100 | result = self._make(map(kwds.pop, %(field_names)r, self)) |
| 101 | if kwds: |
| 102 | raise ValueError('Got unexpected field names: %%r' %% kwds.keys()) |
Georg Brandl | c28e1fa | 2008-06-10 19:20:26 +0000 | [diff] [blame] | 103 | return result \n |
| 104 | def __getnewargs__(self): |
| 105 | return tuple(self) \n\n''' % locals() |
Guido van Rossum | d59da4b | 2007-05-22 18:11:13 +0000 | [diff] [blame] | 106 | for i, name in enumerate(field_names): |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 107 | template += ' %s = property(itemgetter(%d))\n' % (name, i) |
| 108 | if verbose: |
| 109 | print(template) |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 110 | |
Georg Brandl | f08a9dd | 2008-06-10 16:57:31 +0000 | [diff] [blame] | 111 | # Execute the template string in a temporary namespace and |
| 112 | # support tracing utilities by setting a value for frame.f_globals['__name__'] |
| 113 | namespace = dict(itemgetter=_itemgetter, __name__='namedtuple_%s' % typename) |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 114 | try: |
| 115 | exec(template, namespace) |
| 116 | except SyntaxError as e: |
Christian Heimes | 99170a5 | 2007-12-19 02:07:34 +0000 | [diff] [blame] | 117 | raise SyntaxError(e.msg + ':\n' + template) from e |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 118 | result = namespace[typename] |
| 119 | |
| 120 | # For pickling to work, the __module__ variable needs to be set to the frame |
| 121 | # where the named tuple is created. Bypass this step in enviroments where |
| 122 | # sys._getframe is not defined (Jython for example). |
Guido van Rossum | d59da4b | 2007-05-22 18:11:13 +0000 | [diff] [blame] | 123 | if hasattr(_sys, '_getframe'): |
Raymond Hettinger | 0f05517 | 2009-01-27 10:06:09 +0000 | [diff] [blame] | 124 | result.__module__ = _sys._getframe(1).f_globals.get('__name__', '__main__') |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 125 | |
Guido van Rossum | d59da4b | 2007-05-22 18:11:13 +0000 | [diff] [blame] | 126 | return result |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 127 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 128 | |
Raymond Hettinger | b8baf63 | 2009-01-14 02:20:07 +0000 | [diff] [blame] | 129 | ######################################################################## |
| 130 | ### Counter |
| 131 | ######################################################################## |
| 132 | |
| 133 | class Counter(dict): |
| 134 | '''Dict subclass for counting hashable items. Sometimes called a bag |
| 135 | or multiset. Elements are stored as dictionary keys and their counts |
| 136 | are stored as dictionary values. |
| 137 | |
| 138 | >>> c = Counter('abracadabra') # count elements from a string |
| 139 | |
| 140 | >>> c.most_common(3) # three most common elements |
| 141 | [('a', 5), ('r', 2), ('b', 2)] |
| 142 | >>> sorted(c) # list all unique elements |
| 143 | ['a', 'b', 'c', 'd', 'r'] |
| 144 | >>> ''.join(sorted(c.elements())) # list elements with repetitions |
| 145 | 'aaaaabbcdrr' |
| 146 | >>> sum(c.values()) # total of all counts |
| 147 | 11 |
| 148 | |
| 149 | >>> c['a'] # count of letter 'a' |
| 150 | 5 |
| 151 | >>> for elem in 'shazam': # update counts from an iterable |
| 152 | ... c[elem] += 1 # by adding 1 to each element's count |
| 153 | >>> c['a'] # now there are seven 'a' |
| 154 | 7 |
| 155 | >>> del c['r'] # remove all 'r' |
| 156 | >>> c['r'] # now there are zero 'r' |
| 157 | 0 |
| 158 | |
| 159 | >>> d = Counter('simsalabim') # make another counter |
| 160 | >>> c.update(d) # add in the second counter |
| 161 | >>> c['a'] # now there are nine 'a' |
| 162 | 9 |
| 163 | |
| 164 | >>> c.clear() # empty the counter |
| 165 | >>> c |
| 166 | Counter() |
| 167 | |
| 168 | Note: If a count is set to zero or reduced to zero, it will remain |
| 169 | in the counter until the entry is deleted or the counter is cleared: |
| 170 | |
| 171 | >>> c = Counter('aaabbc') |
| 172 | >>> c['b'] -= 2 # reduce the count of 'b' by two |
| 173 | >>> c.most_common() # 'b' is still in, but its count is zero |
| 174 | [('a', 3), ('c', 1), ('b', 0)] |
| 175 | |
| 176 | ''' |
| 177 | # References: |
| 178 | # http://en.wikipedia.org/wiki/Multiset |
| 179 | # http://www.gnu.org/software/smalltalk/manual-base/html_node/Bag.html |
| 180 | # http://www.demo2s.com/Tutorial/Cpp/0380__set-multiset/Catalog0380__set-multiset.htm |
| 181 | # http://code.activestate.com/recipes/259174/ |
| 182 | # Knuth, TAOCP Vol. II section 4.6.3 |
| 183 | |
Raymond Hettinger | 4d2073a | 2009-01-20 03:41:22 +0000 | [diff] [blame] | 184 | def __init__(self, iterable=None, **kwds): |
Raymond Hettinger | b8baf63 | 2009-01-14 02:20:07 +0000 | [diff] [blame] | 185 | '''Create a new, empty Counter object. And if given, count elements |
| 186 | from an input iterable. Or, initialize the count from another mapping |
| 187 | of elements to their counts. |
| 188 | |
| 189 | >>> c = Counter() # a new, empty counter |
| 190 | >>> c = Counter('gallahad') # a new counter from an iterable |
| 191 | >>> c = Counter({'a': 4, 'b': 2}) # a new counter from a mapping |
Raymond Hettinger | 4d2073a | 2009-01-20 03:41:22 +0000 | [diff] [blame] | 192 | >>> c = Counter(a=4, b=2) # a new counter from keyword args |
Raymond Hettinger | b8baf63 | 2009-01-14 02:20:07 +0000 | [diff] [blame] | 193 | |
| 194 | ''' |
Raymond Hettinger | 4d2073a | 2009-01-20 03:41:22 +0000 | [diff] [blame] | 195 | self.update(iterable, **kwds) |
Raymond Hettinger | b8baf63 | 2009-01-14 02:20:07 +0000 | [diff] [blame] | 196 | |
| 197 | def __missing__(self, key): |
| 198 | 'The count of elements not in the Counter is zero.' |
| 199 | # Needed so that self[missing_item] does not raise KeyError |
| 200 | return 0 |
| 201 | |
| 202 | def most_common(self, n=None): |
| 203 | '''List the n most common elements and their counts from the most |
| 204 | common to the least. If n is None, then list all element counts. |
| 205 | |
| 206 | >>> Counter('abracadabra').most_common(3) |
| 207 | [('a', 5), ('r', 2), ('b', 2)] |
| 208 | |
| 209 | ''' |
| 210 | # Emulate Bag.sortedByCount from Smalltalk |
| 211 | if n is None: |
| 212 | return sorted(self.items(), key=_itemgetter(1), reverse=True) |
| 213 | return _heapq.nlargest(n, self.items(), key=_itemgetter(1)) |
| 214 | |
| 215 | def elements(self): |
| 216 | '''Iterator over elements repeating each as many times as its count. |
| 217 | |
| 218 | >>> c = Counter('ABCABC') |
| 219 | >>> sorted(c.elements()) |
| 220 | ['A', 'A', 'B', 'B', 'C', 'C'] |
| 221 | |
| 222 | # Knuth's example for prime factors of 1836: 2**2 * 3**3 * 17**1 |
| 223 | >>> prime_factors = Counter({2: 2, 3: 3, 17: 1}) |
| 224 | >>> product = 1 |
| 225 | >>> for factor in prime_factors.elements(): # loop over factors |
| 226 | ... product *= factor # and multiply them |
| 227 | >>> product |
| 228 | 1836 |
| 229 | |
| 230 | Note, if an element's count has been set to zero or is a negative |
| 231 | number, elements() will ignore it. |
| 232 | |
| 233 | ''' |
| 234 | # Emulate Bag.do from Smalltalk and Multiset.begin from C++. |
| 235 | return _chain.from_iterable(_starmap(_repeat, self.items())) |
| 236 | |
| 237 | # Override dict methods where necessary |
| 238 | |
| 239 | @classmethod |
| 240 | def fromkeys(cls, iterable, v=None): |
| 241 | # There is no equivalent method for counters because setting v=1 |
| 242 | # means that no element can have a count greater than one. |
| 243 | raise NotImplementedError( |
| 244 | 'Counter.fromkeys() is undefined. Use Counter(iterable) instead.') |
| 245 | |
Raymond Hettinger | 4d2073a | 2009-01-20 03:41:22 +0000 | [diff] [blame] | 246 | def update(self, iterable=None, **kwds): |
Raymond Hettinger | b8baf63 | 2009-01-14 02:20:07 +0000 | [diff] [blame] | 247 | '''Like dict.update() but add counts instead of replacing them. |
| 248 | |
| 249 | Source can be an iterable, a dictionary, or another Counter instance. |
| 250 | |
| 251 | >>> c = Counter('which') |
| 252 | >>> c.update('witch') # add elements from another iterable |
| 253 | >>> d = Counter('watch') |
| 254 | >>> c.update(d) # add elements from another counter |
| 255 | >>> c['h'] # four 'h' in which, witch, and watch |
| 256 | 4 |
| 257 | |
| 258 | ''' |
| 259 | # The regular dict.update() operation makes no sense here because the |
| 260 | # replace behavior results in the some of original untouched counts |
| 261 | # being mixed-in with all of the other counts for a mismash that |
| 262 | # doesn't have a straight-forward interpretation in most counting |
Raymond Hettinger | 4d2073a | 2009-01-20 03:41:22 +0000 | [diff] [blame] | 263 | # contexts. Instead, we implement straight-addition. Both the inputs |
| 264 | # and outputs are allowed to contain zero and negative counts. |
Raymond Hettinger | b8baf63 | 2009-01-14 02:20:07 +0000 | [diff] [blame] | 265 | |
| 266 | if iterable is not None: |
| 267 | if isinstance(iterable, Mapping): |
Raymond Hettinger | dd01f8f | 2009-01-22 09:09:55 +0000 | [diff] [blame] | 268 | if self: |
| 269 | for elem, count in iterable.items(): |
| 270 | self[elem] += count |
| 271 | else: |
| 272 | dict.update(self, iterable) # fast path when counter is empty |
Raymond Hettinger | b8baf63 | 2009-01-14 02:20:07 +0000 | [diff] [blame] | 273 | else: |
| 274 | for elem in iterable: |
| 275 | self[elem] += 1 |
Raymond Hettinger | 4d2073a | 2009-01-20 03:41:22 +0000 | [diff] [blame] | 276 | if kwds: |
| 277 | self.update(kwds) |
Raymond Hettinger | b8baf63 | 2009-01-14 02:20:07 +0000 | [diff] [blame] | 278 | |
| 279 | def copy(self): |
| 280 | 'Like dict.copy() but returns a Counter instance instead of a dict.' |
| 281 | return Counter(self) |
| 282 | |
Raymond Hettinger | 4d2073a | 2009-01-20 03:41:22 +0000 | [diff] [blame] | 283 | def __delitem__(self, elem): |
| 284 | 'Like dict.__delitem__() but does not raise KeyError for missing values.' |
| 285 | if elem in self: |
| 286 | dict.__delitem__(self, elem) |
| 287 | |
Raymond Hettinger | b8baf63 | 2009-01-14 02:20:07 +0000 | [diff] [blame] | 288 | def __repr__(self): |
| 289 | if not self: |
| 290 | return '%s()' % self.__class__.__name__ |
| 291 | items = ', '.join(map('%r: %r'.__mod__, self.most_common())) |
| 292 | return '%s({%s})' % (self.__class__.__name__, items) |
| 293 | |
Raymond Hettinger | 4d2073a | 2009-01-20 03:41:22 +0000 | [diff] [blame] | 294 | # Multiset-style mathematical operations discussed in: |
| 295 | # Knuth TAOCP Volume II section 4.6.3 exercise 19 |
| 296 | # and at http://en.wikipedia.org/wiki/Multiset |
| 297 | # |
Raymond Hettinger | 4d2073a | 2009-01-20 03:41:22 +0000 | [diff] [blame] | 298 | # Outputs guaranteed to only include positive counts. |
| 299 | # |
| 300 | # To strip negative and zero counts, add-in an empty counter: |
| 301 | # c += Counter() |
| 302 | |
| 303 | def __add__(self, other): |
| 304 | '''Add counts from two counters. |
| 305 | |
| 306 | >>> Counter('abbb') + Counter('bcc') |
| 307 | Counter({'b': 4, 'c': 2, 'a': 1}) |
| 308 | |
| 309 | ''' |
| 310 | if not isinstance(other, Counter): |
| 311 | return NotImplemented |
| 312 | result = Counter() |
| 313 | for elem in set(self) | set(other): |
| 314 | newcount = self[elem] + other[elem] |
| 315 | if newcount > 0: |
| 316 | result[elem] = newcount |
| 317 | return result |
| 318 | |
| 319 | def __sub__(self, other): |
| 320 | ''' Subtract count, but keep only results with positive counts. |
| 321 | |
| 322 | >>> Counter('abbbc') - Counter('bccd') |
| 323 | Counter({'b': 2, 'a': 1}) |
| 324 | |
| 325 | ''' |
| 326 | if not isinstance(other, Counter): |
| 327 | return NotImplemented |
| 328 | result = Counter() |
Raymond Hettinger | e0d1b9f | 2009-01-21 20:36:27 +0000 | [diff] [blame] | 329 | for elem in set(self) | set(other): |
| 330 | newcount = self[elem] - other[elem] |
Raymond Hettinger | 4d2073a | 2009-01-20 03:41:22 +0000 | [diff] [blame] | 331 | if newcount > 0: |
| 332 | result[elem] = newcount |
| 333 | return result |
| 334 | |
| 335 | def __or__(self, other): |
| 336 | '''Union is the maximum of value in either of the input counters. |
| 337 | |
| 338 | >>> Counter('abbb') | Counter('bcc') |
| 339 | Counter({'b': 3, 'c': 2, 'a': 1}) |
| 340 | |
| 341 | ''' |
| 342 | if not isinstance(other, Counter): |
| 343 | return NotImplemented |
| 344 | _max = max |
| 345 | result = Counter() |
| 346 | for elem in set(self) | set(other): |
| 347 | newcount = _max(self[elem], other[elem]) |
| 348 | if newcount > 0: |
| 349 | result[elem] = newcount |
| 350 | return result |
| 351 | |
| 352 | def __and__(self, other): |
| 353 | ''' Intersection is the minimum of corresponding counts. |
| 354 | |
| 355 | >>> Counter('abbb') & Counter('bcc') |
| 356 | Counter({'b': 1}) |
| 357 | |
| 358 | ''' |
| 359 | if not isinstance(other, Counter): |
| 360 | return NotImplemented |
| 361 | _min = min |
| 362 | result = Counter() |
| 363 | if len(self) < len(other): |
| 364 | self, other = other, self |
| 365 | for elem in filter(self.__contains__, other): |
| 366 | newcount = _min(self[elem], other[elem]) |
| 367 | if newcount > 0: |
| 368 | result[elem] = newcount |
| 369 | return result |
| 370 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 371 | |
Raymond Hettinger | 48b8b66 | 2008-02-05 01:53:00 +0000 | [diff] [blame] | 372 | ################################################################################ |
| 373 | ### UserDict |
| 374 | ################################################################################ |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 375 | |
Raymond Hettinger | 48b8b66 | 2008-02-05 01:53:00 +0000 | [diff] [blame] | 376 | class UserDict(MutableMapping): |
| 377 | |
| 378 | # Start by filling-out the abstract methods |
| 379 | def __init__(self, dict=None, **kwargs): |
| 380 | self.data = {} |
| 381 | if dict is not None: |
| 382 | self.update(dict) |
| 383 | if len(kwargs): |
| 384 | self.update(kwargs) |
| 385 | def __len__(self): return len(self.data) |
| 386 | def __getitem__(self, key): |
| 387 | if key in self.data: |
| 388 | return self.data[key] |
| 389 | if hasattr(self.__class__, "__missing__"): |
| 390 | return self.__class__.__missing__(self, key) |
| 391 | raise KeyError(key) |
| 392 | def __setitem__(self, key, item): self.data[key] = item |
| 393 | def __delitem__(self, key): del self.data[key] |
| 394 | def __iter__(self): |
| 395 | return iter(self.data) |
| 396 | |
Raymond Hettinger | 554c8b8 | 2008-02-05 22:54:43 +0000 | [diff] [blame] | 397 | # Modify __contains__ to work correctly when __missing__ is present |
| 398 | def __contains__(self, key): |
| 399 | return key in self.data |
Raymond Hettinger | 48b8b66 | 2008-02-05 01:53:00 +0000 | [diff] [blame] | 400 | |
| 401 | # Now, add the methods in dicts but not in MutableMapping |
| 402 | def __repr__(self): return repr(self.data) |
| 403 | def copy(self): |
| 404 | if self.__class__ is UserDict: |
| 405 | return UserDict(self.data.copy()) |
| 406 | import copy |
| 407 | data = self.data |
| 408 | try: |
| 409 | self.data = {} |
| 410 | c = copy.copy(self) |
| 411 | finally: |
| 412 | self.data = data |
| 413 | c.update(self) |
| 414 | return c |
| 415 | @classmethod |
| 416 | def fromkeys(cls, iterable, value=None): |
| 417 | d = cls() |
| 418 | for key in iterable: |
| 419 | d[key] = value |
| 420 | return d |
| 421 | |
Raymond Hettinger | 48b8b66 | 2008-02-05 01:53:00 +0000 | [diff] [blame] | 422 | |
| 423 | |
| 424 | ################################################################################ |
Raymond Hettinger | 53dbe39 | 2008-02-12 20:03:09 +0000 | [diff] [blame] | 425 | ### UserList |
| 426 | ################################################################################ |
| 427 | |
| 428 | class UserList(MutableSequence): |
| 429 | """A more or less complete user-defined wrapper around list objects.""" |
| 430 | def __init__(self, initlist=None): |
| 431 | self.data = [] |
| 432 | if initlist is not None: |
| 433 | # XXX should this accept an arbitrary sequence? |
| 434 | if type(initlist) == type(self.data): |
| 435 | self.data[:] = initlist |
| 436 | elif isinstance(initlist, UserList): |
| 437 | self.data[:] = initlist.data[:] |
| 438 | else: |
| 439 | self.data = list(initlist) |
| 440 | def __repr__(self): return repr(self.data) |
| 441 | def __lt__(self, other): return self.data < self.__cast(other) |
| 442 | def __le__(self, other): return self.data <= self.__cast(other) |
| 443 | def __eq__(self, other): return self.data == self.__cast(other) |
| 444 | def __ne__(self, other): return self.data != self.__cast(other) |
| 445 | def __gt__(self, other): return self.data > self.__cast(other) |
| 446 | def __ge__(self, other): return self.data >= self.__cast(other) |
| 447 | def __cast(self, other): |
| 448 | return other.data if isinstance(other, UserList) else other |
Raymond Hettinger | 53dbe39 | 2008-02-12 20:03:09 +0000 | [diff] [blame] | 449 | def __contains__(self, item): return item in self.data |
| 450 | def __len__(self): return len(self.data) |
| 451 | def __getitem__(self, i): return self.data[i] |
| 452 | def __setitem__(self, i, item): self.data[i] = item |
| 453 | def __delitem__(self, i): del self.data[i] |
| 454 | def __add__(self, other): |
| 455 | if isinstance(other, UserList): |
| 456 | return self.__class__(self.data + other.data) |
| 457 | elif isinstance(other, type(self.data)): |
| 458 | return self.__class__(self.data + other) |
| 459 | return self.__class__(self.data + list(other)) |
| 460 | def __radd__(self, other): |
| 461 | if isinstance(other, UserList): |
| 462 | return self.__class__(other.data + self.data) |
| 463 | elif isinstance(other, type(self.data)): |
| 464 | return self.__class__(other + self.data) |
| 465 | return self.__class__(list(other) + self.data) |
| 466 | def __iadd__(self, other): |
| 467 | if isinstance(other, UserList): |
| 468 | self.data += other.data |
| 469 | elif isinstance(other, type(self.data)): |
| 470 | self.data += other |
| 471 | else: |
| 472 | self.data += list(other) |
| 473 | return self |
| 474 | def __mul__(self, n): |
| 475 | return self.__class__(self.data*n) |
| 476 | __rmul__ = __mul__ |
| 477 | def __imul__(self, n): |
| 478 | self.data *= n |
| 479 | return self |
| 480 | def append(self, item): self.data.append(item) |
| 481 | def insert(self, i, item): self.data.insert(i, item) |
| 482 | def pop(self, i=-1): return self.data.pop(i) |
| 483 | def remove(self, item): self.data.remove(item) |
| 484 | def count(self, item): return self.data.count(item) |
| 485 | def index(self, item, *args): return self.data.index(item, *args) |
| 486 | def reverse(self): self.data.reverse() |
| 487 | def sort(self, *args, **kwds): self.data.sort(*args, **kwds) |
| 488 | def extend(self, other): |
| 489 | if isinstance(other, UserList): |
| 490 | self.data.extend(other.data) |
| 491 | else: |
| 492 | self.data.extend(other) |
| 493 | |
| 494 | |
| 495 | |
| 496 | ################################################################################ |
Raymond Hettinger | b3a65f8 | 2008-02-21 22:11:37 +0000 | [diff] [blame] | 497 | ### UserString |
| 498 | ################################################################################ |
| 499 | |
| 500 | class UserString(Sequence): |
| 501 | def __init__(self, seq): |
| 502 | if isinstance(seq, str): |
| 503 | self.data = seq |
| 504 | elif isinstance(seq, UserString): |
| 505 | self.data = seq.data[:] |
| 506 | else: |
| 507 | self.data = str(seq) |
| 508 | def __str__(self): return str(self.data) |
| 509 | def __repr__(self): return repr(self.data) |
| 510 | def __int__(self): return int(self.data) |
Raymond Hettinger | b3a65f8 | 2008-02-21 22:11:37 +0000 | [diff] [blame] | 511 | def __float__(self): return float(self.data) |
| 512 | def __complex__(self): return complex(self.data) |
| 513 | def __hash__(self): return hash(self.data) |
| 514 | |
| 515 | def __eq__(self, string): |
| 516 | if isinstance(string, UserString): |
| 517 | return self.data == string.data |
| 518 | return self.data == string |
| 519 | def __ne__(self, string): |
| 520 | if isinstance(string, UserString): |
| 521 | return self.data != string.data |
| 522 | return self.data != string |
| 523 | def __lt__(self, string): |
| 524 | if isinstance(string, UserString): |
| 525 | return self.data < string.data |
| 526 | return self.data < string |
| 527 | def __le__(self, string): |
| 528 | if isinstance(string, UserString): |
| 529 | return self.data <= string.data |
| 530 | return self.data <= string |
| 531 | def __gt__(self, string): |
| 532 | if isinstance(string, UserString): |
| 533 | return self.data > string.data |
| 534 | return self.data > string |
| 535 | def __ge__(self, string): |
| 536 | if isinstance(string, UserString): |
| 537 | return self.data >= string.data |
| 538 | return self.data >= string |
| 539 | |
| 540 | def __contains__(self, char): |
| 541 | if isinstance(char, UserString): |
| 542 | char = char.data |
| 543 | return char in self.data |
| 544 | |
| 545 | def __len__(self): return len(self.data) |
| 546 | def __getitem__(self, index): return self.__class__(self.data[index]) |
| 547 | def __add__(self, other): |
| 548 | if isinstance(other, UserString): |
| 549 | return self.__class__(self.data + other.data) |
| 550 | elif isinstance(other, str): |
| 551 | return self.__class__(self.data + other) |
| 552 | return self.__class__(self.data + str(other)) |
| 553 | def __radd__(self, other): |
| 554 | if isinstance(other, str): |
| 555 | return self.__class__(other + self.data) |
| 556 | return self.__class__(str(other) + self.data) |
| 557 | def __mul__(self, n): |
| 558 | return self.__class__(self.data*n) |
| 559 | __rmul__ = __mul__ |
| 560 | def __mod__(self, args): |
| 561 | return self.__class__(self.data % args) |
| 562 | |
| 563 | # the following methods are defined in alphabetical order: |
| 564 | def capitalize(self): return self.__class__(self.data.capitalize()) |
| 565 | def center(self, width, *args): |
| 566 | return self.__class__(self.data.center(width, *args)) |
| 567 | def count(self, sub, start=0, end=_sys.maxsize): |
| 568 | if isinstance(sub, UserString): |
| 569 | sub = sub.data |
| 570 | return self.data.count(sub, start, end) |
| 571 | def encode(self, encoding=None, errors=None): # XXX improve this? |
| 572 | if encoding: |
| 573 | if errors: |
| 574 | return self.__class__(self.data.encode(encoding, errors)) |
| 575 | return self.__class__(self.data.encode(encoding)) |
| 576 | return self.__class__(self.data.encode()) |
| 577 | def endswith(self, suffix, start=0, end=_sys.maxsize): |
| 578 | return self.data.endswith(suffix, start, end) |
| 579 | def expandtabs(self, tabsize=8): |
| 580 | return self.__class__(self.data.expandtabs(tabsize)) |
| 581 | def find(self, sub, start=0, end=_sys.maxsize): |
| 582 | if isinstance(sub, UserString): |
| 583 | sub = sub.data |
| 584 | return self.data.find(sub, start, end) |
| 585 | def format(self, *args, **kwds): |
| 586 | return self.data.format(*args, **kwds) |
| 587 | def index(self, sub, start=0, end=_sys.maxsize): |
| 588 | return self.data.index(sub, start, end) |
| 589 | def isalpha(self): return self.data.isalpha() |
| 590 | def isalnum(self): return self.data.isalnum() |
| 591 | def isdecimal(self): return self.data.isdecimal() |
| 592 | def isdigit(self): return self.data.isdigit() |
| 593 | def isidentifier(self): return self.data.isidentifier() |
| 594 | def islower(self): return self.data.islower() |
| 595 | def isnumeric(self): return self.data.isnumeric() |
| 596 | def isspace(self): return self.data.isspace() |
| 597 | def istitle(self): return self.data.istitle() |
| 598 | def isupper(self): return self.data.isupper() |
| 599 | def join(self, seq): return self.data.join(seq) |
| 600 | def ljust(self, width, *args): |
| 601 | return self.__class__(self.data.ljust(width, *args)) |
| 602 | def lower(self): return self.__class__(self.data.lower()) |
| 603 | def lstrip(self, chars=None): return self.__class__(self.data.lstrip(chars)) |
| 604 | def partition(self, sep): |
| 605 | return self.data.partition(sep) |
| 606 | def replace(self, old, new, maxsplit=-1): |
| 607 | if isinstance(old, UserString): |
| 608 | old = old.data |
| 609 | if isinstance(new, UserString): |
| 610 | new = new.data |
| 611 | return self.__class__(self.data.replace(old, new, maxsplit)) |
| 612 | def rfind(self, sub, start=0, end=_sys.maxsize): |
| 613 | return self.data.rfind(sub, start, end) |
| 614 | def rindex(self, sub, start=0, end=_sys.maxsize): |
| 615 | return self.data.rindex(sub, start, end) |
| 616 | def rjust(self, width, *args): |
| 617 | return self.__class__(self.data.rjust(width, *args)) |
| 618 | def rpartition(self, sep): |
| 619 | return self.data.rpartition(sep) |
| 620 | def rstrip(self, chars=None): |
| 621 | return self.__class__(self.data.rstrip(chars)) |
| 622 | def split(self, sep=None, maxsplit=-1): |
| 623 | return self.data.split(sep, maxsplit) |
| 624 | def rsplit(self, sep=None, maxsplit=-1): |
| 625 | return self.data.rsplit(sep, maxsplit) |
| 626 | def splitlines(self, keepends=0): return self.data.splitlines(keepends) |
| 627 | def startswith(self, prefix, start=0, end=_sys.maxsize): |
| 628 | return self.data.startswith(prefix, start, end) |
| 629 | def strip(self, chars=None): return self.__class__(self.data.strip(chars)) |
| 630 | def swapcase(self): return self.__class__(self.data.swapcase()) |
| 631 | def title(self): return self.__class__(self.data.title()) |
| 632 | def translate(self, *args): |
| 633 | return self.__class__(self.data.translate(*args)) |
| 634 | def upper(self): return self.__class__(self.data.upper()) |
| 635 | def zfill(self, width): return self.__class__(self.data.zfill(width)) |
| 636 | |
| 637 | |
| 638 | |
| 639 | ################################################################################ |
Raymond Hettinger | 48b8b66 | 2008-02-05 01:53:00 +0000 | [diff] [blame] | 640 | ### Simple tests |
| 641 | ################################################################################ |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 642 | |
| 643 | if __name__ == '__main__': |
Thomas Wouters | 1b7f891 | 2007-09-19 03:06:30 +0000 | [diff] [blame] | 644 | # verify that instances can be pickled |
Guido van Rossum | 99603b0 | 2007-07-20 00:22:32 +0000 | [diff] [blame] | 645 | from pickle import loads, dumps |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 646 | Point = namedtuple('Point', 'x, y', True) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 647 | p = Point(x=10, y=20) |
| 648 | assert p == loads(dumps(p)) |
| 649 | |
Guido van Rossum | 3d392eb | 2007-11-16 00:35:22 +0000 | [diff] [blame] | 650 | # test and demonstrate ability to override methods |
Christian Heimes | 043d6f6 | 2008-01-07 17:19:16 +0000 | [diff] [blame] | 651 | class Point(namedtuple('Point', 'x y')): |
Christian Heimes | 25bb783 | 2008-01-11 16:17:00 +0000 | [diff] [blame] | 652 | __slots__ = () |
Christian Heimes | 043d6f6 | 2008-01-07 17:19:16 +0000 | [diff] [blame] | 653 | @property |
| 654 | def hypot(self): |
| 655 | return (self.x ** 2 + self.y ** 2) ** 0.5 |
Christian Heimes | 790c823 | 2008-01-07 21:14:23 +0000 | [diff] [blame] | 656 | def __str__(self): |
Christian Heimes | 25bb783 | 2008-01-11 16:17:00 +0000 | [diff] [blame] | 657 | return 'Point: x=%6.3f y=%6.3f hypot=%6.3f' % (self.x, self.y, self.hypot) |
Christian Heimes | 043d6f6 | 2008-01-07 17:19:16 +0000 | [diff] [blame] | 658 | |
Christian Heimes | 25bb783 | 2008-01-11 16:17:00 +0000 | [diff] [blame] | 659 | for p in Point(3, 4), Point(14, 5/7.): |
Christian Heimes | 790c823 | 2008-01-07 21:14:23 +0000 | [diff] [blame] | 660 | print (p) |
Christian Heimes | 043d6f6 | 2008-01-07 17:19:16 +0000 | [diff] [blame] | 661 | |
| 662 | class Point(namedtuple('Point', 'x y')): |
| 663 | 'Point class with optimized _make() and _replace() without error-checking' |
Christian Heimes | 25bb783 | 2008-01-11 16:17:00 +0000 | [diff] [blame] | 664 | __slots__ = () |
Christian Heimes | 043d6f6 | 2008-01-07 17:19:16 +0000 | [diff] [blame] | 665 | _make = classmethod(tuple.__new__) |
| 666 | def _replace(self, _map=map, **kwds): |
Christian Heimes | 2380ac7 | 2008-01-09 00:17:24 +0000 | [diff] [blame] | 667 | return self._make(_map(kwds.get, ('x', 'y'), self)) |
Christian Heimes | 043d6f6 | 2008-01-07 17:19:16 +0000 | [diff] [blame] | 668 | |
| 669 | print(Point(11, 22)._replace(x=100)) |
Guido van Rossum | 3d392eb | 2007-11-16 00:35:22 +0000 | [diff] [blame] | 670 | |
Christian Heimes | 25bb783 | 2008-01-11 16:17:00 +0000 | [diff] [blame] | 671 | Point3D = namedtuple('Point3D', Point._fields + ('z',)) |
| 672 | print(Point3D.__doc__) |
| 673 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 674 | import doctest |
Guido van Rossum | 8ce8a78 | 2007-11-01 19:42:39 +0000 | [diff] [blame] | 675 | TestResults = namedtuple('TestResults', 'failed attempted') |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 676 | print(TestResults(*doctest.testmod())) |