| 1 |
'''This module implements specialized container datatypes providing |
| 2 |
alternatives to Python's general purpose built-in containers, dict, |
| 3 |
list, set, and tuple. |
| 4 |
|
| 5 |
* namedtuple factory function for creating tuple subclasses with named fields |
| 6 |
* deque list-like container with fast appends and pops on either end |
| 7 |
* ChainMap dict-like class for creating a single view of multiple mappings |
| 8 |
* Counter dict subclass for counting hashable objects |
| 9 |
* OrderedDict dict subclass that remembers the order entries were added |
| 10 |
* defaultdict dict subclass that calls a factory function to supply missing values |
| 11 |
* UserDict wrapper around dictionary objects for easier dict subclassing |
| 12 |
* UserList wrapper around list objects for easier list subclassing |
| 13 |
* UserString wrapper around string objects for easier string subclassing |
| 14 |
|
| 15 |
''' |
| 16 |
|
| 17 |
__all__ = [ |
| 18 |
'ChainMap', |
| 19 |
'Counter', |
| 20 |
'OrderedDict', |
| 21 |
'UserDict', |
| 22 |
'UserList', |
| 23 |
'UserString', |
| 24 |
'defaultdict', |
| 25 |
'deque', |
| 26 |
'namedtuple', |
| 27 |
] |
| 28 |
|
| 29 |
import _collections_abc |
| 30 |
import sys as _sys |
| 31 |
|
| 32 |
from itertools import chain as _chain |
| 33 |
from itertools import repeat as _repeat |
| 34 |
from itertools import starmap as _starmap |
| 35 |
from keyword import iskeyword as _iskeyword |
| 36 |
from operator import eq as _eq |
| 37 |
from operator import itemgetter as _itemgetter |
| 38 |
from reprlib import recursive_repr as _recursive_repr |
| 39 |
from _weakref import proxy as _proxy |
| 40 |
|
| 41 |
try: |
| 42 |
from _collections import deque |
| 43 |
except ImportError: |
| 44 |
pass |
| 45 |
else: |
| 46 |
_collections_abc.MutableSequence.register(deque) |
| 47 |
|
| 48 |
try: |
| 49 |
from _collections import defaultdict |
| 50 |
except ImportError: |
| 51 |
pass |
| 52 |
|
| 53 |
try: |
| 54 |
from __pypy__ import newdict |
| 55 |
except ImportError: |
| 56 |
newdict = lambda _: {} |
| 57 |
|
| 58 |
|
| 59 |
|
| 60 |
|
| 61 |
|
| 62 |
|
| 63 |
class _OrderedDictKeysView(_collections_abc.KeysView): |
| 64 |
|
| 65 |
def __reversed__(self): |
| 66 |
yield from reversed(self._mapping) |
| 67 |
|
| 68 |
class _OrderedDictItemsView(_collections_abc.ItemsView): |
| 69 |
|
| 70 |
def __reversed__(self): |
| 71 |
for key in reversed(self._mapping): |
| 72 |
yield (key, self._mapping[key]) |
| 73 |
|
| 74 |
class _OrderedDictValuesView(_collections_abc.ValuesView): |
| 75 |
|
| 76 |
def __reversed__(self): |
| 77 |
for key in reversed(self._mapping): |
| 78 |
yield self._mapping[key] |
| 79 |
|
| 80 |
class _Link(object): |
| 81 |
__slots__ = 'prev', 'next', 'key', '__weakref__' |
| 82 |
|
| 83 |
class OrderedDict(dict): |
| 84 |
'Dictionary that remembers insertion order' |
| 85 |
|
| 86 |
|
| 87 |
|
| 88 |
|
| 89 |
|
| 90 |
|
| 91 |
|
| 92 |
|
| 93 |
|
| 94 |
|
| 95 |
|
| 96 |
|
| 97 |
|
| 98 |
def __new__(cls, /, *args, **kwds): |
| 99 |
"Create the ordered dict object and set up the underlying structures." |
| 100 |
self = dict.__new__(cls) |
| 101 |
self.__hardroot = _Link() |
| 102 |
self.__root = root = _proxy(self.__hardroot) |
| 103 |
root.prev = root.next = root |
| 104 |
self.__map = {} |
| 105 |
return self |
| 106 |
|
| 107 |
def __init__(self, other=(), /, **kwds): |
| 108 |
'''Initialize an ordered dictionary. The signature is the same as |
| 109 |
regular dictionaries. Keyword argument order is preserved. |
| 110 |
''' |
| 111 |
self.__update(other, **kwds) |
| 112 |
|
| 113 |
def __setitem__(self, key, value, |
| 114 |
dict_setitem=dict.__setitem__, proxy=_proxy, Link=_Link): |
| 115 |
'od.__setitem__(i, y) <==> od[i]=y' |
| 116 |
|
| 117 |
|
| 118 |
if key not in self: |
| 119 |
self.__map[key] = link = Link() |
| 120 |
root = self.__root |
| 121 |
last = root.prev |
| 122 |
link.prev, link.next, link.key = last, root, key |
| 123 |
last.next = link |
| 124 |
root.prev = proxy(link) |
| 125 |
dict_setitem(self, key, value) |
| 126 |
|
| 127 |
def __delitem__(self, key, dict_delitem=dict.__delitem__): |
| 128 |
'od.__delitem__(y) <==> del od[y]' |
| 129 |
|
| 130 |
|
| 131 |
dict_delitem(self, key) |
| 132 |
link = self.__map.pop(key) |
| 133 |
link_prev = link.prev |
| 134 |
link_next = link.next |
| 135 |
link_prev.next = link_next |
| 136 |
link_next.prev = link_prev |
| 137 |
link.prev = None |
| 138 |
link.next = None |
| 139 |
|
| 140 |
def __iter__(self): |
| 141 |
'od.__iter__() <==> iter(od)' |
| 142 |
|
| 143 |
root = self.__root |
| 144 |
curr = root.next |
| 145 |
while curr is not root: |
| 146 |
yield curr.key |
| 147 |
curr = curr.next |
| 148 |
|
| 149 |
def __reversed__(self): |
| 150 |
'od.__reversed__() <==> reversed(od)' |
| 151 |
|
| 152 |
root = self.__root |
| 153 |
curr = root.prev |
| 154 |
while curr is not root: |
| 155 |
yield curr.key |
| 156 |
curr = curr.prev |
| 157 |
|
| 158 |
def clear(self): |
| 159 |
'od.clear() -> None. Remove all items from od.' |
| 160 |
root = self.__root |
| 161 |
root.prev = root.next = root |
| 162 |
self.__map.clear() |
| 163 |
dict.clear(self) |
| 164 |
|
| 165 |
def popitem(self, last=True): |
| 166 |
'''Remove and return a (key, value) pair from the dictionary. |
| 167 |
|
| 168 |
Pairs are returned in LIFO order if last is true or FIFO order if false. |
| 169 |
''' |
| 170 |
if not self: |
| 171 |
raise KeyError('dictionary is empty') |
| 172 |
root = self.__root |
| 173 |
if last: |
| 174 |
link = root.prev |
| 175 |
link_prev = link.prev |
| 176 |
link_prev.next = root |
| 177 |
root.prev = link_prev |
| 178 |
else: |
| 179 |
link = root.next |
| 180 |
link_next = link.next |
| 181 |
root.next = link_next |
| 182 |
link_next.prev = root |
| 183 |
key = link.key |
| 184 |
del self.__map[key] |
| 185 |
value = dict.pop(self, key) |
| 186 |
return key, value |
| 187 |
|
| 188 |
def move_to_end(self, key, last=True): |
| 189 |
'''Move an existing element to the end (or beginning if last is false). |
| 190 |
|
| 191 |
Raise KeyError if the element does not exist. |
| 192 |
''' |
| 193 |
link = self.__map[key] |
| 194 |
link_prev = link.prev |
| 195 |
link_next = link.next |
| 196 |
soft_link = link_next.prev |
| 197 |
link_prev.next = link_next |
| 198 |
link_next.prev = link_prev |
| 199 |
root = self.__root |
| 200 |
if last: |
| 201 |
last = root.prev |
| 202 |
link.prev = last |
| 203 |
link.next = root |
| 204 |
root.prev = soft_link |
| 205 |
last.next = link |
| 206 |
else: |
| 207 |
first = root.next |
| 208 |
link.prev = root |
| 209 |
link.next = first |
| 210 |
first.prev = soft_link |
| 211 |
root.next = link |
| 212 |
|
| 213 |
def __sizeof__(self): |
| 214 |
sizeof = _sys.getsizeof |
| 215 |
n = len(self) + 1 |
| 216 |
size = sizeof(self.__dict__) |
| 217 |
size += sizeof(self.__map) * 2 |
| 218 |
size += sizeof(self.__hardroot) * n |
| 219 |
size += sizeof(self.__root) * n |
| 220 |
return size |
| 221 |
|
| 222 |
update = __update = _collections_abc.MutableMapping.update |
| 223 |
|
| 224 |
def keys(self): |
| 225 |
"D.keys() -> a set-like object providing a view on D's keys" |
| 226 |
return _OrderedDictKeysView(self) |
| 227 |
|
| 228 |
def items(self): |
| 229 |
"D.items() -> a set-like object providing a view on D's items" |
| 230 |
return _OrderedDictItemsView(self) |
| 231 |
|
| 232 |
def values(self): |
| 233 |
"D.values() -> an object providing a view on D's values" |
| 234 |
return _OrderedDictValuesView(self) |
| 235 |
|
| 236 |
__ne__ = _collections_abc.MutableMapping.__ne__ |
| 237 |
|
| 238 |
__marker = object() |
| 239 |
|
| 240 |
def pop(self, key, default=__marker): |
| 241 |
'''od.pop(k[,d]) -> v, remove specified key and return the corresponding |
| 242 |
value. If key is not found, d is returned if given, otherwise KeyError |
| 243 |
is raised. |
| 244 |
|
| 245 |
''' |
| 246 |
marker = self.__marker |
| 247 |
result = dict.pop(self, key, marker) |
| 248 |
if result is not marker: |
| 249 |
|
| 250 |
link = self.__map.pop(key) |
| 251 |
link_prev = link.prev |
| 252 |
link_next = link.next |
| 253 |
link_prev.next = link_next |
| 254 |
link_next.prev = link_prev |
| 255 |
link.prev = None |
| 256 |
link.next = None |
| 257 |
return result |
| 258 |
if default is marker: |
| 259 |
raise KeyError(key) |
| 260 |
return default |
| 261 |
|
| 262 |
def setdefault(self, key, default=None): |
| 263 |
'''Insert key with a value of default if key is not in the dictionary. |
| 264 |
|
| 265 |
Return the value for key if key is in the dictionary, else default. |
| 266 |
''' |
| 267 |
if key in self: |
| 268 |
return self[key] |
| 269 |
self[key] = default |
| 270 |
return default |
| 271 |
|
| 272 |
@_recursive_repr() |
| 273 |
def __repr__(self): |
| 274 |
'od.__repr__() <==> repr(od)' |
| 275 |
if not self: |
| 276 |
return '%s()' % (self.__class__.__name__,) |
| 277 |
return '%s(%r)' % (self.__class__.__name__, list(self.items())) |
| 278 |
|
| 279 |
def __reduce__(self): |
| 280 |
'Return state information for pickling' |
| 281 |
state = self.__getstate__() |
| 282 |
if state: |
| 283 |
if isinstance(state, tuple): |
| 284 |
state, slots = state |
| 285 |
else: |
| 286 |
slots = {} |
| 287 |
state = state.copy() |
| 288 |
slots = slots.copy() |
| 289 |
for k in vars(OrderedDict()): |
| 290 |
state.pop(k, None) |
| 291 |
slots.pop(k, None) |
| 292 |
if slots: |
| 293 |
state = state, slots |
| 294 |
else: |
| 295 |
state = state or None |
| 296 |
return self.__class__, (), state, None, iter(self.items()) |
| 297 |
|
| 298 |
def copy(self): |
| 299 |
'od.copy() -> a shallow copy of od' |
| 300 |
return self.__class__(self) |
| 301 |
|
| 302 |
@classmethod |
| 303 |
def fromkeys(cls, iterable, value=None): |
| 304 |
'''Create a new ordered dictionary with keys from iterable and values set to value. |
| 305 |
''' |
| 306 |
self = cls() |
| 307 |
for key in iterable: |
| 308 |
self[key] = value |
| 309 |
return self |
| 310 |
|
| 311 |
def __eq__(self, other): |
| 312 |
'''od.__eq__(y) <==> od==y. Comparison to another OD is order-sensitive |
| 313 |
while comparison to a regular mapping is order-insensitive. |
| 314 |
|
| 315 |
''' |
| 316 |
if isinstance(other, OrderedDict): |
| 317 |
return dict.__eq__(self, other) and all(map(_eq, self, other)) |
| 318 |
return dict.__eq__(self, other) |
| 319 |
|
| 320 |
def __ior__(self, other): |
| 321 |
self.update(other) |
| 322 |
return self |
| 323 |
|
| 324 |
def __or__(self, other): |
| 325 |
if not isinstance(other, dict): |
| 326 |
return NotImplemented |
| 327 |
new = self.__class__(self) |
| 328 |
new.update(other) |
| 329 |
return new |
| 330 |
|
| 331 |
def __ror__(self, other): |
| 332 |
if not isinstance(other, dict): |
| 333 |
return NotImplemented |
| 334 |
new = self.__class__(other) |
| 335 |
new.update(self) |
| 336 |
return new |
| 337 |
|
| 338 |
|
| 339 |
try: |
| 340 |
from _collections import OrderedDict |
| 341 |
except ImportError: |
| 342 |
|
| 343 |
pass |
| 344 |
|
| 345 |
|
| 346 |
|
| 347 |
|
| 348 |
|
| 349 |
|
| 350 |
try: |
| 351 |
from _collections import _tuplegetter |
| 352 |
except ImportError: |
| 353 |
_tuplegetter = lambda index, doc: property(_itemgetter(index), doc=doc) |
| 354 |
|
| 355 |
def namedtuple(typename, field_names, *, rename=False, defaults=None, module=None): |
| 356 |
"""Returns a new subclass of tuple with named fields. |
| 357 |
|
| 358 |
>>> Point = namedtuple('Point', ['x', 'y']) |
| 359 |
>>> Point.__doc__ # docstring for the new class |
| 360 |
'Point(x, y)' |
| 361 |
>>> p = Point(11, y=22) # instantiate with positional args or keywords |
| 362 |
>>> p[0] + p[1] # indexable like a plain tuple |
| 363 |
33 |
| 364 |
>>> x, y = p # unpack like a regular tuple |
| 365 |
>>> x, y |
| 366 |
(11, 22) |
| 367 |
>>> p.x + p.y # fields also accessible by name |
| 368 |
33 |
| 369 |
>>> d = p._asdict() # convert to a dictionary |
| 370 |
>>> d['x'] |
| 371 |
11 |
| 372 |
>>> Point(**d) # convert from a dictionary |
| 373 |
Point(x=11, y=22) |
| 374 |
>>> p._replace(x=100) # _replace() is like str.replace() but targets named fields |
| 375 |
Point(x=100, y=22) |
| 376 |
|
| 377 |
""" |
| 378 |
|
| 379 |
|
| 380 |
|
| 381 |
if isinstance(field_names, str): |
| 382 |
field_names = field_names.replace(',', ' ').split() |
| 383 |
field_names = list(map(str, field_names)) |
| 384 |
typename = _sys.intern(str(typename)) |
| 385 |
|
| 386 |
if rename: |
| 387 |
seen = set() |
| 388 |
for index, name in enumerate(field_names): |
| 389 |
if (not name.isidentifier() |
| 390 |
or _iskeyword(name) |
| 391 |
or name.startswith('_') |
| 392 |
or name in seen): |
| 393 |
field_names[index] = f'_{index}' |
| 394 |
seen.add(name) |
| 395 |
|
| 396 |
for name in [typename] + field_names: |
| 397 |
if type(name) is not str: |
| 398 |
raise TypeError('Type names and field names must be strings') |
| 399 |
if not name.isidentifier(): |
| 400 |
raise ValueError('Type names and field names must be valid ' |
| 401 |
f'identifiers: {name!r}') |
| 402 |
if _iskeyword(name): |
| 403 |
raise ValueError('Type names and field names cannot be a ' |
| 404 |
f'keyword: {name!r}') |
| 405 |
|
| 406 |
seen = set() |
| 407 |
for name in field_names: |
| 408 |
if name.startswith('_') and not rename: |
| 409 |
raise ValueError('Field names cannot start with an underscore: ' |
| 410 |
f'{name!r}') |
| 411 |
if name in seen: |
| 412 |
raise ValueError(f'Encountered duplicate field name: {name!r}') |
| 413 |
seen.add(name) |
| 414 |
|
| 415 |
field_defaults = {} |
| 416 |
if defaults is not None: |
| 417 |
defaults = tuple(defaults) |
| 418 |
if len(defaults) > len(field_names): |
| 419 |
raise TypeError('Got more default values than field names') |
| 420 |
field_defaults = dict(reversed(list(zip(reversed(field_names), |
| 421 |
reversed(defaults))))) |
| 422 |
|
| 423 |
|
| 424 |
field_names = tuple(map(_sys.intern, field_names)) |
| 425 |
num_fields = len(field_names) |
| 426 |
arg_list = ', '.join(field_names) |
| 427 |
if num_fields == 1: |
| 428 |
arg_list += ',' |
| 429 |
repr_fmt = '(' + ', '.join(f'{name}=%r' for name in field_names) + ')' |
| 430 |
tuple_new = tuple.__new__ |
| 431 |
_dict, _tuple, _len, _map, _zip = dict, tuple, len, map, zip |
| 432 |
|
| 433 |
|
| 434 |
|
| 435 |
|
| 436 |
namespace = newdict('module') |
| 437 |
namespace['_tuple_new'] = tuple_new |
| 438 |
namespace['__builtins__'] = {} |
| 439 |
namespace['__name__'] = f'namedtuple_{typename}' |
| 440 |
code = f'lambda _cls, {arg_list}: _tuple_new(_cls, ({arg_list}))' |
| 441 |
__new__ = eval(code, namespace) |
| 442 |
__new__.__name__ = '__new__' |
| 443 |
__new__.__doc__ = f'Create new instance of {typename}({arg_list})' |
| 444 |
if defaults is not None: |
| 445 |
__new__.__defaults__ = defaults |
| 446 |
|
| 447 |
@classmethod |
| 448 |
def _make(cls, iterable): |
| 449 |
result = tuple_new(cls, iterable) |
| 450 |
if _len(result) != num_fields: |
| 451 |
raise TypeError(f'Expected {num_fields} arguments, got {len(result)}') |
| 452 |
return result |
| 453 |
|
| 454 |
_make.__func__.__doc__ = (f'Make a new {typename} object from a sequence ' |
| 455 |
'or iterable') |
| 456 |
|
| 457 |
|
| 458 |
|
| 459 |
|
| 460 |
parameters = "\n".join(f" {field}=_not_given," for field in field_names) |
| 461 |
if field_names: |
| 462 |
star = " *," |
| 463 |
else: |
| 464 |
star = "" |
| 465 |
arguments = "\n".join( |
| 466 |
f" {field}=_self[{i}] if {field} is _not_given else {field}," |
| 467 |
for i, field in enumerate(field_names) |
| 468 |
) |
| 469 |
code = f"""\ |
| 470 |
_not_given = object() |
| 471 |
_type = type |
| 472 |
_ValueError = ValueError |
| 473 |
_list = list |
| 474 |
def _replace( |
| 475 |
_self, |
| 476 |
/, |
| 477 |
{star} |
| 478 |
{parameters} |
| 479 |
**_kwargs, |
| 480 |
): |
| 481 |
if _kwargs: |
| 482 |
raise _ValueError(f"Got unexpected field names: {{_list(_kwargs)!r}}") |
| 483 |
else: |
| 484 |
return _type(_self)( |
| 485 |
{arguments} |
| 486 |
) |
| 487 |
""" |
| 488 |
exec(code, namespace) |
| 489 |
_replace = namespace["_replace"] |
| 490 |
_replace.__doc__ = (f'Return a new {typename} object replacing specified ' |
| 491 |
'fields with new values') |
| 492 |
|
| 493 |
def __repr__(self): |
| 494 |
'Return a nicely formatted representation string' |
| 495 |
return self.__class__.__name__ + repr_fmt % self |
| 496 |
|
| 497 |
def _asdict(self): |
| 498 |
'Return a new dict which maps field names to their values.' |
| 499 |
return _dict(_zip(self._fields, self)) |
| 500 |
|
| 501 |
def __getnewargs__(self): |
| 502 |
'Return self as a plain tuple. Used by copy and pickle.' |
| 503 |
return _tuple(self) |
| 504 |
|
| 505 |
|
| 506 |
for method in ( |
| 507 |
__new__, |
| 508 |
_make.__func__, |
| 509 |
_replace, |
| 510 |
__repr__, |
| 511 |
_asdict, |
| 512 |
__getnewargs__, |
| 513 |
): |
| 514 |
method.__qualname__ = f'{typename}.{method.__name__}' |
| 515 |
|
| 516 |
|
| 517 |
|
| 518 |
class_namespace = { |
| 519 |
'__doc__': f'{typename}({arg_list})', |
| 520 |
'__slots__': (), |
| 521 |
'_fields': field_names, |
| 522 |
'_field_defaults': field_defaults, |
| 523 |
'__new__': __new__, |
| 524 |
'_make': _make, |
| 525 |
'_replace': _replace, |
| 526 |
'__repr__': __repr__, |
| 527 |
'_asdict': _asdict, |
| 528 |
'__getnewargs__': __getnewargs__, |
| 529 |
'__match_args__': field_names, |
| 530 |
} |
| 531 |
for index, name in enumerate(field_names): |
| 532 |
doc = _sys.intern(f'Alias for field number {index}') |
| 533 |
class_namespace[name] = _tuplegetter(index, doc) |
| 534 |
|
| 535 |
result = type(typename, (tuple,), class_namespace) |
| 536 |
|
| 537 |
|
| 538 |
|
| 539 |
|
| 540 |
|
| 541 |
|
| 542 |
if module is None: |
| 543 |
try: |
| 544 |
module = _sys._getframe(1).f_globals.get('__name__', '__main__') |
| 545 |
except (AttributeError, ValueError): |
| 546 |
pass |
| 547 |
if module is not None: |
| 548 |
result.__module__ = module |
| 549 |
|
| 550 |
return result |
| 551 |
|
| 552 |
|
| 553 |
|
| 554 |
|
| 555 |
|
| 556 |
|
| 557 |
def _count_elements(mapping, iterable): |
| 558 |
'Tally elements from the iterable.' |
| 559 |
mapping_get = mapping.get |
| 560 |
for elem in iterable: |
| 561 |
mapping[elem] = mapping_get(elem, 0) + 1 |
| 562 |
|
| 563 |
try: |
| 564 |
from _collections import _count_elements |
| 565 |
except ImportError: |
| 566 |
pass |
| 567 |
|
| 568 |
class Counter(dict): |
| 569 |
'''Dict subclass for counting hashable items. Sometimes called a bag |
| 570 |
or multiset. Elements are stored as dictionary keys and their counts |
| 571 |
are stored as dictionary values. |
| 572 |
|
| 573 |
>>> c = Counter('abcdeabcdabcaba') # count elements from a string |
| 574 |
|
| 575 |
>>> c.most_common(3) # three most common elements |
| 576 |
[('a', 5), ('b', 4), ('c', 3)] |
| 577 |
>>> sorted(c) # list all unique elements |
| 578 |
['a', 'b', 'c', 'd', 'e'] |
| 579 |
>>> ''.join(sorted(c.elements())) # list elements with repetitions |
| 580 |
'aaaaabbbbcccdde' |
| 581 |
>>> sum(c.values()) # total of all counts |
| 582 |
15 |
| 583 |
|
| 584 |
>>> c['a'] # count of letter 'a' |
| 585 |
5 |
| 586 |
>>> for elem in 'shazam': # update counts from an iterable |
| 587 |
... c[elem] += 1 # by adding 1 to each element's count |
| 588 |
>>> c['a'] # now there are seven 'a' |
| 589 |
7 |
| 590 |
>>> del c['b'] # remove all 'b' |
| 591 |
>>> c['b'] # now there are zero 'b' |
| 592 |
0 |
| 593 |
|
| 594 |
>>> d = Counter('simsalabim') # make another counter |
| 595 |
>>> c.update(d) # add in the second counter |
| 596 |
>>> c['a'] # now there are nine 'a' |
| 597 |
9 |
| 598 |
|
| 599 |
>>> c.clear() # empty the counter |
| 600 |
>>> c |
| 601 |
Counter() |
| 602 |
|
| 603 |
Note: If a count is set to zero or reduced to zero, it will remain |
| 604 |
in the counter until the entry is deleted or the counter is cleared: |
| 605 |
|
| 606 |
>>> c = Counter('aaabbc') |
| 607 |
>>> c['b'] -= 2 # reduce the count of 'b' by two |
| 608 |
>>> c.most_common() # 'b' is still in, but its count is zero |
| 609 |
[('a', 3), ('c', 1), ('b', 0)] |
| 610 |
|
| 611 |
''' |
| 612 |
|
| 613 |
|
| 614 |
|
| 615 |
|
| 616 |
|
| 617 |
|
| 618 |
|
| 619 |
def __init__(self, iterable=None, /, **kwds): |
| 620 |
'''Create a new, empty Counter object. And if given, count elements |
| 621 |
from an input iterable. Or, initialize the count from another mapping |
| 622 |
of elements to their counts. |
| 623 |
|
| 624 |
>>> c = Counter() # a new, empty counter |
| 625 |
>>> c = Counter('gallahad') # a new counter from an iterable |
| 626 |
>>> c = Counter({'a': 4, 'b': 2}) # a new counter from a mapping |
| 627 |
>>> c = Counter(a=4, b=2) # a new counter from keyword args |
| 628 |
|
| 629 |
''' |
| 630 |
super().__init__() |
| 631 |
self.update(iterable, **kwds) |
| 632 |
|
| 633 |
def __missing__(self, key): |
| 634 |
'The count of elements not in the Counter is zero.' |
| 635 |
|
| 636 |
return 0 |
| 637 |
|
| 638 |
def total(self): |
| 639 |
'Sum of the counts' |
| 640 |
return sum(self.values()) |
| 641 |
|
| 642 |
def most_common(self, n=None): |
| 643 |
'''List the n most common elements and their counts from the most |
| 644 |
common to the least. If n is None, then list all element counts. |
| 645 |
|
| 646 |
>>> Counter('abracadabra').most_common(3) |
| 647 |
[('a', 5), ('b', 2), ('r', 2)] |
| 648 |
|
| 649 |
''' |
| 650 |
|
| 651 |
if n is None: |
| 652 |
return sorted(self.items(), key=_itemgetter(1), reverse=True) |
| 653 |
|
| 654 |
|
| 655 |
import heapq |
| 656 |
return heapq.nlargest(n, self.items(), key=_itemgetter(1)) |
| 657 |
|
| 658 |
def elements(self): |
| 659 |
'''Iterator over elements repeating each as many times as its count. |
| 660 |
|
| 661 |
>>> c = Counter('ABCABC') |
| 662 |
>>> sorted(c.elements()) |
| 663 |
['A', 'A', 'B', 'B', 'C', 'C'] |
| 664 |
|
| 665 |
# Knuth's example for prime factors of 1836: 2**2 * 3**3 * 17**1 |
| 666 |
>>> import math |
| 667 |
>>> prime_factors = Counter({2: 2, 3: 3, 17: 1}) |
| 668 |
>>> math.prod(prime_factors.elements()) |
| 669 |
1836 |
| 670 |
|
| 671 |
Note, if an element's count has been set to zero or is a negative |
| 672 |
number, elements() will ignore it. |
| 673 |
|
| 674 |
''' |
| 675 |
|
| 676 |
return _chain.from_iterable(_starmap(_repeat, self.items())) |
| 677 |
|
| 678 |
|
| 679 |
|
| 680 |
@classmethod |
| 681 |
def fromkeys(cls, iterable, v=None): |
| 682 |
|
| 683 |
|
| 684 |
|
| 685 |
|
| 686 |
|
| 687 |
|
| 688 |
|
| 689 |
raise NotImplementedError( |
| 690 |
'Counter.fromkeys() is undefined. Use Counter(iterable) instead.') |
| 691 |
|
| 692 |
def update(self, iterable=None, /, **kwds): |
| 693 |
'''Like dict.update() but add counts instead of replacing them. |
| 694 |
|
| 695 |
Source can be an iterable, a dictionary, or another Counter instance. |
| 696 |
|
| 697 |
>>> c = Counter('which') |
| 698 |
>>> c.update('witch') # add elements from another iterable |
| 699 |
>>> d = Counter('watch') |
| 700 |
>>> c.update(d) # add elements from another counter |
| 701 |
>>> c['h'] # four 'h' in which, witch, and watch |
| 702 |
4 |
| 703 |
|
| 704 |
''' |
| 705 |
|
| 706 |
|
| 707 |
|
| 708 |
|
| 709 |
|
| 710 |
|
| 711 |
|
| 712 |
if iterable is not None: |
| 713 |
if isinstance(iterable, _collections_abc.Mapping): |
| 714 |
if self: |
| 715 |
self_get = self.get |
| 716 |
for elem, count in iterable.items(): |
| 717 |
self[elem] = count + self_get(elem, 0) |
| 718 |
else: |
| 719 |
|
| 720 |
super().update(iterable) |
| 721 |
else: |
| 722 |
_count_elements(self, iterable) |
| 723 |
if kwds: |
| 724 |
self.update(kwds) |
| 725 |
|
| 726 |
def subtract(self, iterable=None, /, **kwds): |
| 727 |
'''Like dict.update() but subtracts counts instead of replacing them. |
| 728 |
Counts can be reduced below zero. Both the inputs and outputs are |
| 729 |
allowed to contain zero and negative counts. |
| 730 |
|
| 731 |
Source can be an iterable, a dictionary, or another Counter instance. |
| 732 |
|
| 733 |
>>> c = Counter('which') |
| 734 |
>>> c.subtract('witch') # subtract elements from another iterable |
| 735 |
>>> c.subtract(Counter('watch')) # subtract elements from another counter |
| 736 |
>>> c['h'] # 2 in which, minus 1 in witch, minus 1 in watch |
| 737 |
0 |
| 738 |
>>> c['w'] # 1 in which, minus 1 in witch, minus 1 in watch |
| 739 |
-1 |
| 740 |
|
| 741 |
''' |
| 742 |
if iterable is not None: |
| 743 |
self_get = self.get |
| 744 |
if isinstance(iterable, _collections_abc.Mapping): |
| 745 |
for elem, count in iterable.items(): |
| 746 |
self[elem] = self_get(elem, 0) - count |
| 747 |
else: |
| 748 |
for elem in iterable: |
| 749 |
self[elem] = self_get(elem, 0) - 1 |
| 750 |
if kwds: |
| 751 |
self.subtract(kwds) |
| 752 |
|
| 753 |
def copy(self): |
| 754 |
'Return a shallow copy.' |
| 755 |
return self.__class__(self) |
| 756 |
|
| 757 |
def __reduce__(self): |
| 758 |
return self.__class__, (dict(self),) |
| 759 |
|
| 760 |
def __delitem__(self, elem): |
| 761 |
'Like dict.__delitem__() but does not raise KeyError for missing values.' |
| 762 |
if elem in self: |
| 763 |
super().__delitem__(elem) |
| 764 |
|
| 765 |
def __repr__(self): |
| 766 |
if not self: |
| 767 |
return f'{self.__class__.__name__}()' |
| 768 |
try: |
| 769 |
|
| 770 |
d = dict(self.most_common()) |
| 771 |
except TypeError: |
| 772 |
|
| 773 |
d = dict(self) |
| 774 |
return f'{self.__class__.__name__}({d!r})' |
| 775 |
|
| 776 |
|
| 777 |
|
| 778 |
|
| 779 |
|
| 780 |
|
| 781 |
|
| 782 |
|
| 783 |
|
| 784 |
|
| 785 |
|
| 786 |
|
| 787 |
|
| 788 |
|
| 789 |
|
| 790 |
|
| 791 |
|
| 792 |
|
| 793 |
|
| 794 |
|
| 795 |
|
| 796 |
|
| 797 |
|
| 798 |
|
| 799 |
|
| 800 |
|
| 801 |
|
| 802 |
|
| 803 |
|
| 804 |
|
| 805 |
|
| 806 |
|
| 807 |
|
| 808 |
|
| 809 |
|
| 810 |
def __eq__(self, other): |
| 811 |
'True if all counts agree. Missing counts are treated as zero.' |
| 812 |
if not isinstance(other, Counter): |
| 813 |
return NotImplemented |
| 814 |
return all(self[e] == other[e] for c in (self, other) for e in c) |
| 815 |
|
| 816 |
def __ne__(self, other): |
| 817 |
'True if any counts disagree. Missing counts are treated as zero.' |
| 818 |
if not isinstance(other, Counter): |
| 819 |
return NotImplemented |
| 820 |
return not self == other |
| 821 |
|
| 822 |
def __le__(self, other): |
| 823 |
'True if all counts in self are a subset of those in other.' |
| 824 |
if not isinstance(other, Counter): |
| 825 |
return NotImplemented |
| 826 |
return all(self[e] <= other[e] for c in (self, other) for e in c) |
| 827 |
|
| 828 |
def __lt__(self, other): |
| 829 |
'True if all counts in self are a proper subset of those in other.' |
| 830 |
if not isinstance(other, Counter): |
| 831 |
return NotImplemented |
| 832 |
return self <= other and self != other |
| 833 |
|
| 834 |
def __ge__(self, other): |
| 835 |
'True if all counts in self are a superset of those in other.' |
| 836 |
if not isinstance(other, Counter): |
| 837 |
return NotImplemented |
| 838 |
return all(self[e] >= other[e] for c in (self, other) for e in c) |
| 839 |
|
| 840 |
def __gt__(self, other): |
| 841 |
'True if all counts in self are a proper superset of those in other.' |
| 842 |
if not isinstance(other, Counter): |
| 843 |
return NotImplemented |
| 844 |
return self >= other and self != other |
| 845 |
|
| 846 |
def __add__(self, other): |
| 847 |
'''Add counts from two counters. |
| 848 |
|
| 849 |
>>> Counter('abbb') + Counter('bcc') |
| 850 |
Counter({'b': 4, 'c': 2, 'a': 1}) |
| 851 |
|
| 852 |
''' |
| 853 |
if not isinstance(other, Counter): |
| 854 |
return NotImplemented |
| 855 |
result = Counter() |
| 856 |
for elem, count in self.items(): |
| 857 |
newcount = count + other[elem] |
| 858 |
if newcount > 0: |
| 859 |
result[elem] = newcount |
| 860 |
for elem, count in other.items(): |
| 861 |
if elem not in self and count > 0: |
| 862 |
result[elem] = count |
| 863 |
return result |
| 864 |
|
| 865 |
def __sub__(self, other): |
| 866 |
''' Subtract count, but keep only results with positive counts. |
| 867 |
|
| 868 |
>>> Counter('abbbc') - Counter('bccd') |
| 869 |
Counter({'b': 2, 'a': 1}) |
| 870 |
|
| 871 |
''' |
| 872 |
if not isinstance(other, Counter): |
| 873 |
return NotImplemented |
| 874 |
result = Counter() |
| 875 |
for elem, count in self.items(): |
| 876 |
newcount = count - other[elem] |
| 877 |
if newcount > 0: |
| 878 |
result[elem] = newcount |
| 879 |
for elem, count in other.items(): |
| 880 |
if elem not in self and count < 0: |
| 881 |
result[elem] = 0 - count |
| 882 |
return result |
| 883 |
|
| 884 |
def __or__(self, other): |
| 885 |
'''Union is the maximum of value in either of the input counters. |
| 886 |
|
| 887 |
>>> Counter('abbb') | Counter('bcc') |
| 888 |
Counter({'b': 3, 'c': 2, 'a': 1}) |
| 889 |
|
| 890 |
''' |
| 891 |
if not isinstance(other, Counter): |
| 892 |
return NotImplemented |
| 893 |
result = Counter() |
| 894 |
for elem, count in self.items(): |
| 895 |
other_count = other[elem] |
| 896 |
newcount = other_count if count < other_count else count |
| 897 |
if newcount > 0: |
| 898 |
result[elem] = newcount |
| 899 |
for elem, count in other.items(): |
| 900 |
if elem not in self and count > 0: |
| 901 |
result[elem] = count |
| 902 |
return result |
| 903 |
|
| 904 |
def __and__(self, other): |
| 905 |
''' Intersection is the minimum of corresponding counts. |
| 906 |
|
| 907 |
>>> Counter('abbb') & Counter('bcc') |
| 908 |
Counter({'b': 1}) |
| 909 |
|
| 910 |
''' |
| 911 |
if not isinstance(other, Counter): |
| 912 |
return NotImplemented |
| 913 |
result = Counter() |
| 914 |
for elem, count in self.items(): |
| 915 |
other_count = other[elem] |
| 916 |
newcount = count if count < other_count else other_count |
| 917 |
if newcount > 0: |
| 918 |
result[elem] = newcount |
| 919 |
return result |
| 920 |
|
| 921 |
def __pos__(self): |
| 922 |
'Adds an empty counter, effectively stripping negative and zero counts' |
| 923 |
result = Counter() |
| 924 |
for elem, count in self.items(): |
| 925 |
if count > 0: |
| 926 |
result[elem] = count |
| 927 |
return result |
| 928 |
|
| 929 |
def __neg__(self): |
| 930 |
'''Subtracts from an empty counter. Strips positive and zero counts, |
| 931 |
and flips the sign on negative counts. |
| 932 |
|
| 933 |
''' |
| 934 |
result = Counter() |
| 935 |
for elem, count in self.items(): |
| 936 |
if count < 0: |
| 937 |
result[elem] = 0 - count |
| 938 |
return result |
| 939 |
|
| 940 |
def _keep_positive(self): |
| 941 |
'''Internal method to strip elements with a negative or zero count''' |
| 942 |
nonpositive = [elem for elem, count in self.items() if not count > 0] |
| 943 |
for elem in nonpositive: |
| 944 |
del self[elem] |
| 945 |
return self |
| 946 |
|
| 947 |
def __iadd__(self, other): |
| 948 |
'''Inplace add from another counter, keeping only positive counts. |
| 949 |
|
| 950 |
>>> c = Counter('abbb') |
| 951 |
>>> c += Counter('bcc') |
| 952 |
>>> c |
| 953 |
Counter({'b': 4, 'c': 2, 'a': 1}) |
| 954 |
|
| 955 |
''' |
| 956 |
for elem, count in other.items(): |
| 957 |
self[elem] += count |
| 958 |
return self._keep_positive() |
| 959 |
|
| 960 |
def __isub__(self, other): |
| 961 |
'''Inplace subtract counter, but keep only results with positive counts. |
| 962 |
|
| 963 |
>>> c = Counter('abbbc') |
| 964 |
>>> c -= Counter('bccd') |
| 965 |
>>> c |
| 966 |
Counter({'b': 2, 'a': 1}) |
| 967 |
|
| 968 |
''' |
| 969 |
for elem, count in other.items(): |
| 970 |
self[elem] -= count |
| 971 |
return self._keep_positive() |
| 972 |
|
| 973 |
def __ior__(self, other): |
| 974 |
'''Inplace union is the maximum of value from either counter. |
| 975 |
|
| 976 |
>>> c = Counter('abbb') |
| 977 |
>>> c |= Counter('bcc') |
| 978 |
>>> c |
| 979 |
Counter({'b': 3, 'c': 2, 'a': 1}) |
| 980 |
|
| 981 |
''' |
| 982 |
for elem, other_count in other.items(): |
| 983 |
count = self[elem] |
| 984 |
if other_count > count: |
| 985 |
self[elem] = other_count |
| 986 |
return self._keep_positive() |
| 987 |
|
| 988 |
def __iand__(self, other): |
| 989 |
'''Inplace intersection is the minimum of corresponding counts. |
| 990 |
|
| 991 |
>>> c = Counter('abbb') |
| 992 |
>>> c &= Counter('bcc') |
| 993 |
>>> c |
| 994 |
Counter({'b': 1}) |
| 995 |
|
| 996 |
''' |
| 997 |
for elem, count in self.items(): |
| 998 |
other_count = other[elem] |
| 999 |
if other_count < count: |
| 1000 |
self[elem] = other_count |
| 1001 |
return self._keep_positive() |
| 1002 |
|
| 1003 |
|
| 1004 |
|
| 1005 |
|
| 1006 |
|
| 1007 |
|
| 1008 |
class ChainMap(_collections_abc.MutableMapping): |
| 1009 |
''' A ChainMap groups multiple dicts (or other mappings) together |
| 1010 |
to create a single, updateable view. |
| 1011 |
|
| 1012 |
The underlying mappings are stored in a list. That list is public and can |
| 1013 |
be accessed or updated using the *maps* attribute. There is no other |
| 1014 |
state. |
| 1015 |
|
| 1016 |
Lookups search the underlying mappings successively until a key is found. |
| 1017 |
In contrast, writes, updates, and deletions only operate on the first |
| 1018 |
mapping. |
| 1019 |
|
| 1020 |
''' |
| 1021 |
|
| 1022 |
def __init__(self, *maps): |
| 1023 |
'''Initialize a ChainMap by setting *maps* to the given mappings. |
| 1024 |
If no mappings are provided, a single empty dictionary is used. |
| 1025 |
|
| 1026 |
''' |
| 1027 |
self.maps = list(maps) or [{}] |
| 1028 |
|
| 1029 |
def __missing__(self, key): |
| 1030 |
raise KeyError(key) |
| 1031 |
|
| 1032 |
def __getitem__(self, key): |
| 1033 |
for mapping in self.maps: |
| 1034 |
try: |
| 1035 |
return mapping[key] |
| 1036 |
except KeyError: |
| 1037 |
pass |
| 1038 |
return self.__missing__(key) |
| 1039 |
|
| 1040 |
def get(self, key, default=None): |
| 1041 |
return self[key] if key in self else default |
| 1042 |
|
| 1043 |
def __len__(self): |
| 1044 |
return len(set().union(*self.maps)) |
| 1045 |
|
| 1046 |
def __iter__(self): |
| 1047 |
d = {} |
| 1048 |
for mapping in reversed(self.maps): |
| 1049 |
d.update(dict.fromkeys(mapping)) |
| 1050 |
return iter(d) |
| 1051 |
|
| 1052 |
def __contains__(self, key): |
| 1053 |
return any(key in m for m in self.maps) |
| 1054 |
|
| 1055 |
def __bool__(self): |
| 1056 |
return any(self.maps) |
| 1057 |
|
| 1058 |
@_recursive_repr() |
| 1059 |
def __repr__(self): |
| 1060 |
return f'{self.__class__.__name__}({", ".join(map(repr, self.maps))})' |
| 1061 |
|
| 1062 |
@classmethod |
| 1063 |
def fromkeys(cls, iterable, *args): |
| 1064 |
'Create a ChainMap with a single dict created from the iterable.' |
| 1065 |
return cls(dict.fromkeys(iterable, *args)) |
| 1066 |
|
| 1067 |
def copy(self): |
| 1068 |
'New ChainMap or subclass with a new copy of maps[0] and refs to maps[1:]' |
| 1069 |
return self.__class__(self.maps[0].copy(), *self.maps[1:]) |
| 1070 |
|
| 1071 |
__copy__ = copy |
| 1072 |
|
| 1073 |
def new_child(self, m=None, **kwargs): |
| 1074 |
'''New ChainMap with a new map followed by all previous maps. |
| 1075 |
If no map is provided, an empty dict is used. |
| 1076 |
Keyword arguments update the map or new empty dict. |
| 1077 |
''' |
| 1078 |
if m is None: |
| 1079 |
m = kwargs |
| 1080 |
elif kwargs: |
| 1081 |
m.update(kwargs) |
| 1082 |
return self.__class__(m, *self.maps) |
| 1083 |
|
| 1084 |
@property |
| 1085 |
def parents(self): |
| 1086 |
'New ChainMap from maps[1:].' |
| 1087 |
return self.__class__(*self.maps[1:]) |
| 1088 |
|
| 1089 |
def __setitem__(self, key, value): |
| 1090 |
self.maps[0][key] = value |
| 1091 |
|
| 1092 |
def __delitem__(self, key): |
| 1093 |
try: |
| 1094 |
del self.maps[0][key] |
| 1095 |
except KeyError: |
| 1096 |
raise KeyError(f'Key not found in the first mapping: {key!r}') |
| 1097 |
|
| 1098 |
def popitem(self): |
| 1099 |
'Remove and return an item pair from maps[0]. Raise KeyError is maps[0] is empty.' |
| 1100 |
try: |
| 1101 |
return self.maps[0].popitem() |
| 1102 |
except KeyError: |
| 1103 |
raise KeyError('No keys found in the first mapping.') |
| 1104 |
|
| 1105 |
def pop(self, key, *args): |
| 1106 |
'Remove *key* from maps[0] and return its value. Raise KeyError if *key* not in maps[0].' |
| 1107 |
try: |
| 1108 |
return self.maps[0].pop(key, *args) |
| 1109 |
except KeyError: |
| 1110 |
raise KeyError(f'Key not found in the first mapping: {key!r}') |
| 1111 |
|
| 1112 |
def clear(self): |
| 1113 |
'Clear maps[0], leaving maps[1:] intact.' |
| 1114 |
self.maps[0].clear() |
| 1115 |
|
| 1116 |
def __ior__(self, other): |
| 1117 |
self.maps[0].update(other) |
| 1118 |
return self |
| 1119 |
|
| 1120 |
def __or__(self, other): |
| 1121 |
if not isinstance(other, _collections_abc.Mapping): |
| 1122 |
return NotImplemented |
| 1123 |
m = self.copy() |
| 1124 |
m.maps[0].update(other) |
| 1125 |
return m |
| 1126 |
|
| 1127 |
def __ror__(self, other): |
| 1128 |
if not isinstance(other, _collections_abc.Mapping): |
| 1129 |
return NotImplemented |
| 1130 |
m = dict(other) |
| 1131 |
for child in reversed(self.maps): |
| 1132 |
m.update(child) |
| 1133 |
return self.__class__(m) |
| 1134 |
|
| 1135 |
|
| 1136 |
|
| 1137 |
|
| 1138 |
|
| 1139 |
|
| 1140 |
class UserDict(_collections_abc.MutableMapping): |
| 1141 |
|
| 1142 |
|
| 1143 |
def __init__(self, dict=None, /, **kwargs): |
| 1144 |
self.data = {} |
| 1145 |
if dict is not None: |
| 1146 |
self.update(dict) |
| 1147 |
if kwargs: |
| 1148 |
self.update(kwargs) |
| 1149 |
|
| 1150 |
def __len__(self): |
| 1151 |
return len(self.data) |
| 1152 |
|
| 1153 |
def __getitem__(self, key): |
| 1154 |
if key in self.data: |
| 1155 |
return self.data[key] |
| 1156 |
if hasattr(self.__class__, "__missing__"): |
| 1157 |
return self.__class__.__missing__(self, key) |
| 1158 |
raise KeyError(key) |
| 1159 |
|
| 1160 |
def __setitem__(self, key, item): |
| 1161 |
self.data[key] = item |
| 1162 |
|
| 1163 |
def __delitem__(self, key): |
| 1164 |
del self.data[key] |
| 1165 |
|
| 1166 |
def __iter__(self): |
| 1167 |
return iter(self.data) |
| 1168 |
|
| 1169 |
|
| 1170 |
def __contains__(self, key): |
| 1171 |
return key in self.data |
| 1172 |
|
| 1173 |
|
| 1174 |
def __repr__(self): |
| 1175 |
return repr(self.data) |
| 1176 |
|
| 1177 |
def __or__(self, other): |
| 1178 |
if isinstance(other, UserDict): |
| 1179 |
return self.__class__(self.data | other.data) |
| 1180 |
if isinstance(other, dict): |
| 1181 |
return self.__class__(self.data | other) |
| 1182 |
return NotImplemented |
| 1183 |
|
| 1184 |
def __ror__(self, other): |
| 1185 |
if isinstance(other, UserDict): |
| 1186 |
return self.__class__(other.data | self.data) |
| 1187 |
if isinstance(other, dict): |
| 1188 |
return self.__class__(other | self.data) |
| 1189 |
return NotImplemented |
| 1190 |
|
| 1191 |
def __ior__(self, other): |
| 1192 |
if isinstance(other, UserDict): |
| 1193 |
self.data |= other.data |
| 1194 |
else: |
| 1195 |
self.data |= other |
| 1196 |
return self |
| 1197 |
|
| 1198 |
def __copy__(self): |
| 1199 |
inst = self.__class__.__new__(self.__class__) |
| 1200 |
inst.__dict__.update(self.__dict__) |
| 1201 |
|
| 1202 |
inst.__dict__["data"] = self.__dict__["data"].copy() |
| 1203 |
return inst |
| 1204 |
|
| 1205 |
def copy(self): |
| 1206 |
if self.__class__ is UserDict: |
| 1207 |
return UserDict(self.data.copy()) |
| 1208 |
import copy |
| 1209 |
data = self.data |
| 1210 |
try: |
| 1211 |
self.data = {} |
| 1212 |
c = copy.copy(self) |
| 1213 |
finally: |
| 1214 |
self.data = data |
| 1215 |
c.update(self) |
| 1216 |
return c |
| 1217 |
|
| 1218 |
@classmethod |
| 1219 |
def fromkeys(cls, iterable, value=None): |
| 1220 |
d = cls() |
| 1221 |
for key in iterable: |
| 1222 |
d[key] = value |
| 1223 |
return d |
| 1224 |
|
| 1225 |
|
| 1226 |
|
| 1227 |
|
| 1228 |
|
| 1229 |
|
| 1230 |
class UserList(_collections_abc.MutableSequence): |
| 1231 |
"""A more or less complete user-defined wrapper around list objects.""" |
| 1232 |
|
| 1233 |
def __init__(self, initlist=None): |
| 1234 |
self.data = [] |
| 1235 |
if initlist is not None: |
| 1236 |
|
| 1237 |
if type(initlist) == type(self.data): |
| 1238 |
self.data[:] = initlist |
| 1239 |
elif isinstance(initlist, UserList): |
| 1240 |
self.data[:] = initlist.data[:] |
| 1241 |
else: |
| 1242 |
self.data = list(initlist) |
| 1243 |
|
| 1244 |
def __repr__(self): |
| 1245 |
return repr(self.data) |
| 1246 |
|
| 1247 |
def __lt__(self, other): |
| 1248 |
return self.data < self.__cast(other) |
| 1249 |
|
| 1250 |
def __le__(self, other): |
| 1251 |
return self.data <= self.__cast(other) |
| 1252 |
|
| 1253 |
def __eq__(self, other): |
| 1254 |
return self.data == self.__cast(other) |
| 1255 |
|
| 1256 |
def __gt__(self, other): |
| 1257 |
return self.data > self.__cast(other) |
| 1258 |
|
| 1259 |
def __ge__(self, other): |
| 1260 |
return self.data >= self.__cast(other) |
| 1261 |
|
| 1262 |
def __cast(self, other): |
| 1263 |
return other.data if isinstance(other, UserList) else other |
| 1264 |
|
| 1265 |
def __contains__(self, item): |
| 1266 |
return item in self.data |
| 1267 |
|
| 1268 |
def __len__(self): |
| 1269 |
return len(self.data) |
| 1270 |
|
| 1271 |
def __getitem__(self, i): |
| 1272 |
if isinstance(i, slice): |
| 1273 |
return self.__class__(self.data[i]) |
| 1274 |
else: |
| 1275 |
return self.data[i] |
| 1276 |
|
| 1277 |
def __setitem__(self, i, item): |
| 1278 |
self.data[i] = item |
| 1279 |
|
| 1280 |
def __delitem__(self, i): |
| 1281 |
del self.data[i] |
| 1282 |
|
| 1283 |
def __add__(self, other): |
| 1284 |
if isinstance(other, UserList): |
| 1285 |
return self.__class__(self.data + other.data) |
| 1286 |
elif isinstance(other, type(self.data)): |
| 1287 |
return self.__class__(self.data + other) |
| 1288 |
return self.__class__(self.data + list(other)) |
| 1289 |
|
| 1290 |
def __radd__(self, other): |
| 1291 |
if isinstance(other, UserList): |
| 1292 |
return self.__class__(other.data + self.data) |
| 1293 |
elif isinstance(other, type(self.data)): |
| 1294 |
return self.__class__(other + self.data) |
| 1295 |
return self.__class__(list(other) + self.data) |
| 1296 |
|
| 1297 |
def __iadd__(self, other): |
| 1298 |
if isinstance(other, UserList): |
| 1299 |
self.data += other.data |
| 1300 |
elif isinstance(other, type(self.data)): |
| 1301 |
self.data += other |
| 1302 |
else: |
| 1303 |
self.data += list(other) |
| 1304 |
return self |
| 1305 |
|
| 1306 |
def __mul__(self, n): |
| 1307 |
return self.__class__(self.data * n) |
| 1308 |
|
| 1309 |
__rmul__ = __mul__ |
| 1310 |
|
| 1311 |
def __imul__(self, n): |
| 1312 |
self.data *= n |
| 1313 |
return self |
| 1314 |
|
| 1315 |
def __copy__(self): |
| 1316 |
inst = self.__class__.__new__(self.__class__) |
| 1317 |
inst.__dict__.update(self.__dict__) |
| 1318 |
|
| 1319 |
inst.__dict__["data"] = self.__dict__["data"][:] |
| 1320 |
return inst |
| 1321 |
|
| 1322 |
def append(self, item): |
| 1323 |
self.data.append(item) |
| 1324 |
|
| 1325 |
def insert(self, i, item): |
| 1326 |
self.data.insert(i, item) |
| 1327 |
|
| 1328 |
def pop(self, i=-1): |
| 1329 |
return self.data.pop(i) |
| 1330 |
|
| 1331 |
def remove(self, item): |
| 1332 |
self.data.remove(item) |
| 1333 |
|
| 1334 |
def clear(self): |
| 1335 |
self.data.clear() |
| 1336 |
|
| 1337 |
def copy(self): |
| 1338 |
return self.__class__(self) |
| 1339 |
|
| 1340 |
def count(self, item): |
| 1341 |
return self.data.count(item) |
| 1342 |
|
| 1343 |
def index(self, item, *args): |
| 1344 |
return self.data.index(item, *args) |
| 1345 |
|
| 1346 |
def reverse(self): |
| 1347 |
self.data.reverse() |
| 1348 |
|
| 1349 |
def sort(self, /, *args, **kwds): |
| 1350 |
self.data.sort(*args, **kwds) |
| 1351 |
|
| 1352 |
def extend(self, other): |
| 1353 |
if isinstance(other, UserList): |
| 1354 |
self.data.extend(other.data) |
| 1355 |
else: |
| 1356 |
self.data.extend(other) |
| 1357 |
|
| 1358 |
|
| 1359 |
|
| 1360 |
|
| 1361 |
|
| 1362 |
|
| 1363 |
class UserString(_collections_abc.Sequence): |
| 1364 |
|
| 1365 |
def __init__(self, seq): |
| 1366 |
if isinstance(seq, str): |
| 1367 |
self.data = seq |
| 1368 |
elif isinstance(seq, UserString): |
| 1369 |
self.data = seq.data[:] |
| 1370 |
else: |
| 1371 |
self.data = str(seq) |
| 1372 |
|
| 1373 |
def __str__(self): |
| 1374 |
return str(self.data) |
| 1375 |
|
| 1376 |
def __repr__(self): |
| 1377 |
return repr(self.data) |
| 1378 |
|
| 1379 |
def __int__(self): |
| 1380 |
return int(self.data) |
| 1381 |
|
| 1382 |
def __float__(self): |
| 1383 |
return float(self.data) |
| 1384 |
|
| 1385 |
def __complex__(self): |
| 1386 |
return complex(self.data) |
| 1387 |
|
| 1388 |
def __hash__(self): |
| 1389 |
return hash(self.data) |
| 1390 |
|
| 1391 |
def __getnewargs__(self): |
| 1392 |
return (self.data[:],) |
| 1393 |
|
| 1394 |
def __eq__(self, string): |
| 1395 |
if isinstance(string, UserString): |
| 1396 |
return self.data == string.data |
| 1397 |
return self.data == string |
| 1398 |
|
| 1399 |
def __lt__(self, string): |
| 1400 |
if isinstance(string, UserString): |
| 1401 |
return self.data < string.data |
| 1402 |
return self.data < string |
| 1403 |
|
| 1404 |
def __le__(self, string): |
| 1405 |
if isinstance(string, UserString): |
| 1406 |
return self.data <= string.data |
| 1407 |
return self.data <= string |
| 1408 |
|
| 1409 |
def __gt__(self, string): |
| 1410 |
if isinstance(string, UserString): |
| 1411 |
return self.data > string.data |
| 1412 |
return self.data > string |
| 1413 |
|
| 1414 |
def __ge__(self, string): |
| 1415 |
if isinstance(string, UserString): |
| 1416 |
return self.data >= string.data |
| 1417 |
return self.data >= string |
| 1418 |
|
| 1419 |
def __contains__(self, char): |
| 1420 |
if isinstance(char, UserString): |
| 1421 |
char = char.data |
| 1422 |
return char in self.data |
| 1423 |
|
| 1424 |
def __len__(self): |
| 1425 |
return len(self.data) |
| 1426 |
|
| 1427 |
def __getitem__(self, index): |
| 1428 |
return self.__class__(self.data[index]) |
| 1429 |
|
| 1430 |
def __add__(self, other): |
| 1431 |
if isinstance(other, UserString): |
| 1432 |
return self.__class__(self.data + other.data) |
| 1433 |
elif isinstance(other, str): |
| 1434 |
return self.__class__(self.data + other) |
| 1435 |
return self.__class__(self.data + str(other)) |
| 1436 |
|
| 1437 |
def __radd__(self, other): |
| 1438 |
if isinstance(other, str): |
| 1439 |
return self.__class__(other + self.data) |
| 1440 |
return self.__class__(str(other) + self.data) |
| 1441 |
|
| 1442 |
def __mul__(self, n): |
| 1443 |
return self.__class__(self.data * n) |
| 1444 |
|
| 1445 |
__rmul__ = __mul__ |
| 1446 |
|
| 1447 |
def __mod__(self, args): |
| 1448 |
return self.__class__(self.data % args) |
| 1449 |
|
| 1450 |
def __rmod__(self, template): |
| 1451 |
return self.__class__(str(template) % self) |
| 1452 |
|
| 1453 |
|
| 1454 |
def capitalize(self): |
| 1455 |
return self.__class__(self.data.capitalize()) |
| 1456 |
|
| 1457 |
def casefold(self): |
| 1458 |
return self.__class__(self.data.casefold()) |
| 1459 |
|
| 1460 |
def center(self, width, *args): |
| 1461 |
return self.__class__(self.data.center(width, *args)) |
| 1462 |
|
| 1463 |
def count(self, sub, start=0, end=_sys.maxsize): |
| 1464 |
if isinstance(sub, UserString): |
| 1465 |
sub = sub.data |
| 1466 |
return self.data.count(sub, start, end) |
| 1467 |
|
| 1468 |
def removeprefix(self, prefix, /): |
| 1469 |
if isinstance(prefix, UserString): |
| 1470 |
prefix = prefix.data |
| 1471 |
return self.__class__(self.data.removeprefix(prefix)) |
| 1472 |
|
| 1473 |
def removesuffix(self, suffix, /): |
| 1474 |
if isinstance(suffix, UserString): |
| 1475 |
suffix = suffix.data |
| 1476 |
return self.__class__(self.data.removesuffix(suffix)) |
| 1477 |
|
| 1478 |
def encode(self, encoding='utf-8', errors='strict'): |
| 1479 |
encoding = 'utf-8' if encoding is None else encoding |
| 1480 |
errors = 'strict' if errors is None else errors |
| 1481 |
return self.data.encode(encoding, errors) |
| 1482 |
|
| 1483 |
def endswith(self, suffix, start=0, end=_sys.maxsize): |
| 1484 |
return self.data.endswith(suffix, start, end) |
| 1485 |
|
| 1486 |
def expandtabs(self, tabsize=8): |
| 1487 |
return self.__class__(self.data.expandtabs(tabsize)) |
| 1488 |
|
| 1489 |
def find(self, sub, start=0, end=_sys.maxsize): |
| 1490 |
if isinstance(sub, UserString): |
| 1491 |
sub = sub.data |
| 1492 |
return self.data.find(sub, start, end) |
| 1493 |
|
| 1494 |
def format(self, /, *args, **kwds): |
| 1495 |
return self.data.format(*args, **kwds) |
| 1496 |
|
| 1497 |
def format_map(self, mapping): |
| 1498 |
return self.data.format_map(mapping) |
| 1499 |
|
| 1500 |
def index(self, sub, start=0, end=_sys.maxsize): |
| 1501 |
return self.data.index(sub, start, end) |
| 1502 |
|
| 1503 |
def isalpha(self): |
| 1504 |
return self.data.isalpha() |
| 1505 |
|
| 1506 |
def isalnum(self): |
| 1507 |
return self.data.isalnum() |
| 1508 |
|
| 1509 |
def isascii(self): |
| 1510 |
return self.data.isascii() |
| 1511 |
|
| 1512 |
def isdecimal(self): |
| 1513 |
return self.data.isdecimal() |
| 1514 |
|
| 1515 |
def isdigit(self): |
| 1516 |
return self.data.isdigit() |
| 1517 |
|
| 1518 |
def isidentifier(self): |
| 1519 |
return self.data.isidentifier() |
| 1520 |
|
| 1521 |
def islower(self): |
| 1522 |
return self.data.islower() |
| 1523 |
|
| 1524 |
def isnumeric(self): |
| 1525 |
return self.data.isnumeric() |
| 1526 |
|
| 1527 |
def isprintable(self): |
| 1528 |
return self.data.isprintable() |
| 1529 |
|
| 1530 |
def isspace(self): |
| 1531 |
return self.data.isspace() |
| 1532 |
|
| 1533 |
def istitle(self): |
| 1534 |
return self.data.istitle() |
| 1535 |
|
| 1536 |
def isupper(self): |
| 1537 |
return self.data.isupper() |
| 1538 |
|
| 1539 |
def join(self, seq): |
| 1540 |
return self.data.join(seq) |
| 1541 |
|
| 1542 |
def ljust(self, width, *args): |
| 1543 |
return self.__class__(self.data.ljust(width, *args)) |
| 1544 |
|
| 1545 |
def lower(self): |
| 1546 |
return self.__class__(self.data.lower()) |
| 1547 |
|
| 1548 |
def lstrip(self, chars=None): |
| 1549 |
return self.__class__(self.data.lstrip(chars)) |
| 1550 |
|
| 1551 |
maketrans = str.maketrans |
| 1552 |
|
| 1553 |
def partition(self, sep): |
| 1554 |
return self.data.partition(sep) |
| 1555 |
|
| 1556 |
def replace(self, old, new, maxsplit=-1): |
| 1557 |
if isinstance(old, UserString): |
| 1558 |
old = old.data |
| 1559 |
if isinstance(new, UserString): |
| 1560 |
new = new.data |
| 1561 |
return self.__class__(self.data.replace(old, new, maxsplit)) |
| 1562 |
|
| 1563 |
def rfind(self, sub, start=0, end=_sys.maxsize): |
| 1564 |
if isinstance(sub, UserString): |
| 1565 |
sub = sub.data |
| 1566 |
return self.data.rfind(sub, start, end) |
| 1567 |
|
| 1568 |
def rindex(self, sub, start=0, end=_sys.maxsize): |
| 1569 |
return self.data.rindex(sub, start, end) |
| 1570 |
|
| 1571 |
def rjust(self, width, *args): |
| 1572 |
return self.__class__(self.data.rjust(width, *args)) |
| 1573 |
|
| 1574 |
def rpartition(self, sep): |
| 1575 |
return self.data.rpartition(sep) |
| 1576 |
|
| 1577 |
def rstrip(self, chars=None): |
| 1578 |
return self.__class__(self.data.rstrip(chars)) |
| 1579 |
|
| 1580 |
def split(self, sep=None, maxsplit=-1): |
| 1581 |
return self.data.split(sep, maxsplit) |
| 1582 |
|
| 1583 |
def rsplit(self, sep=None, maxsplit=-1): |
| 1584 |
return self.data.rsplit(sep, maxsplit) |
| 1585 |
|
| 1586 |
def splitlines(self, keepends=False): |
| 1587 |
return self.data.splitlines(keepends) |
| 1588 |
|
| 1589 |
def startswith(self, prefix, start=0, end=_sys.maxsize): |
| 1590 |
return self.data.startswith(prefix, start, end) |
| 1591 |
|
| 1592 |
def strip(self, chars=None): |
| 1593 |
return self.__class__(self.data.strip(chars)) |
| 1594 |
|
| 1595 |
def swapcase(self): |
| 1596 |
return self.__class__(self.data.swapcase()) |
| 1597 |
|
| 1598 |
def title(self): |
| 1599 |
return self.__class__(self.data.title()) |
| 1600 |
|
| 1601 |
def translate(self, *args): |
| 1602 |
return self.__class__(self.data.translate(*args)) |
| 1603 |
|
| 1604 |
def upper(self): |
| 1605 |
return self.__class__(self.data.upper()) |
| 1606 |
|
| 1607 |
def zfill(self, width): |
| 1608 |
return self.__class__(self.data.zfill(width)) |