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