this module implements specialized container datatypes providing alternatives to python s general purpose builtin containers dict list set and tuple namedtuple factory function for creating tuple subclasses with named fields deque listlike container with fast appends and pops on either end chainmap dictlike class for creating a single view of multiple mappings counter dict subclass for counting hashable objects ordereddict dict subclass that remembers the order entries were added defaultdict dict subclass that calls a factory function to supply missing values userdict wrapper around dictionary objects for easier dict subclassing userlist wrapper around list objects for easier list subclassing userstring wrapper around string objects for easier string subclassing ordereddict an inherited dict maps keys to values the inherited dict provides getitem len contains and get the remaining methods are orderaware bigo running times for all methods are the same as regular dictionaries the internal self map dict maps keys to links in a doubly linked list the circular doubly linked list starts and ends with a sentinel element the sentinel element never gets deleted this simplifies the algorithm the sentinel is in self hardroot with a weakref proxy in self root the prev links are weakref proxies to prevent circular references individual links are kept alive by the hard reference in self map those hard references disappear when a key is deleted from an ordereddict initialize an ordered dictionary the signature is the same as regular dictionaries keyword argument order is preserved setting a new item creates a new link at the end of the linked list and the inherited dictionary is updated with the new keyvalue pair deleting an existing item uses self map to find the link which gets removed by updating the links in the predecessor and successor nodes traverse the linked list in order traverse the linked list in reverse order remove and return a key value pair from the dictionary pairs are returned in lifo order if last is true or fifo order if false move an existing element to the end or beginning if last is false raise keyerror if the element does not exist od popk d v remove specified key and return the corresponding value if key is not found d is returned if given otherwise keyerror is raised the same as in delitem insert key with a value of default if key is not in the dictionary return the value for key if key is in the dictionary else default create a new ordered dictionary with keys from iterable and values set to value od eqy ody comparison to another od is ordersensitive while comparison to a regular mapping is orderinsensitive leave the pure python version in place namedtuple returns a new subclass of tuple with named fields point namedtuple point x y point doc docstring for the new class pointx y p point11 y22 instantiate with positional args or keywords p0 p1 indexable like a plain tuple 33 x y p unpack like a regular tuple x y 11 22 p x p y fields also accessible by name 33 d p asdict convert to a dictionary d x 11 pointd convert from a dictionary pointx11 y22 p replacex100 replace is like str replace but targets named fields pointx100 y22 validate the field names at the user s option either generate an error message or automatically replace the field name with a valid name variables used in the methods and docstrings create all the named tuple methods to be added to the class namespace modify function metadata to help with introspection and debugging buildup the class namespace dictionary and use type to build the result class for pickling to work the module variable needs to be set to the frame where the named tuple is created bypass this step in environments where sys getframe is not defined jython for example or sys getframe is not defined for arguments greater than 0 ironpython or where the user has specified a particular module counter dict subclass for counting hashable items sometimes called a bag or multiset elements are stored as dictionary keys and their counts are stored as dictionary values c counter abcdeabcdabcaba count elements from a string c mostcommon3 three most common elements a 5 b 4 c 3 sortedc list all unique elements a b c d e joinsortedc elements list elements with repetitions aaaaabbbbcccdde sumc values total of all counts 15 c a count of letter a 5 for elem in shazam update counts from an iterable celem 1 by adding 1 to each element s count c a now there are seven a 7 del c b remove all b c b now there are zero b 0 d counter simsalabim make another counter c updated add in the second counter c a now there are nine a 9 c clear empty the counter c counter note if a count is set to zero or reduced to zero it will remain in the counter until the entry is deleted or the counter is cleared c counter aaabbc c b 2 reduce the count of b by two c mostcommon b is still in but its count is zero a 3 c 1 b 0 references http en wikipedia orgwikimultiset http www gnu orgsoftwaresmalltalkmanualbasehtmlnodebag html http www demo2s comtutorialcpp0380setmultisetcatalog0380setmultiset htm http code activestate comrecipes259174 knuth taocp vol ii section 4 6 3 create a new empty counter object and if given count elements from an input iterable or initialize the count from another mapping of elements to their counts c counter a new empty counter c counter gallahad a new counter from an iterable c counter a 4 b 2 a new counter from a mapping c countera4 b2 a new counter from keyword args needed so that selfmissingitem does not raise keyerror list the n most common elements and their counts from the most common to the least if n is none then list all element counts counter abracadabra mostcommon3 a 5 b 2 r 2 emulate bag sortedbycount from smalltalk lazy import to speedup python startup time iterator over elements repeating each as many times as its count c counter abcabc sortedc elements a a b b c c knuth s example for prime factors of 1836 22 33 171 import math primefactors counter2 2 3 3 17 1 math prodprimefactors elements 1836 note if an element s count has been set to zero or is a negative number elements will ignore it emulate bag do from smalltalk and multiset begin from c override dict methods where necessary there is no equivalent method for counters because the semantics would be ambiguous in cases such as counter fromkeys aaabbc v2 initializing counters to zero values isn t necessary because zero is already the default value for counter lookups initializing to one is easily accomplished with countersetiterable for more exotic cases create a dictionary first using a dictionary comprehension or dict fromkeys like dict update but add counts instead of replacing them source can be an iterable a dictionary or another counter instance c counter which c update witch add elements from another iterable d counter watch c updated add elements from another counter c h four h in which witch and watch 4 the regular dict update operation makes no sense here because the replace behavior results in the some of original untouched counts being mixedin with all of the other counts for a mismash that doesn t have a straightforward interpretation in most counting contexts instead we implement straightaddition both the inputs and outputs are allowed to contain zero and negative counts fast path when counter is empty like dict update but subtracts counts instead of replacing them counts can be reduced below zero both the inputs and outputs are allowed to contain zero and negative counts source can be an iterable a dictionary or another counter instance c counter which c subtract witch subtract elements from another iterable c subtractcounter watch subtract elements from another counter c h 2 in which minus 1 in witch minus 1 in watch 0 c w 1 in which minus 1 in witch minus 1 in watch 1 dict preserves the ordering returned by mostcommon handle case where values are not orderable multisetstyle mathematical operations discussed in knuth taocp volume ii section 4 6 3 exercise 19 and at http en wikipedia orgwikimultiset outputs guaranteed to only include positive counts to strip negative and zero counts addin an empty counter c counter results are ordered according to when an element is first encountered in the left operand and then by the order encountered in the right operand when the multiplicities are all zero or one multiset operations are guaranteed to be equivalent to the corresponding operations for regular sets given counter multisets such as cp countera1 b0 c1 cq counterc1 d0 e1 the corresponding regular sets would be sp a c sq c e all of the following relations would hold setcp cq sp sq setcp cq sp sq setcp cq sp sq setcp cq sp sq cp cq sp sq cp cq sp sq cp cq sp sq cp cq sp sq cp cq sp sq cp cq sp sq add counts from two counters counter abbb counter bcc counter b 4 c 2 a 1 subtract count but keep only results with positive counts counter abbbc counter bccd counter b 2 a 1 union is the maximum of value in either of the input counters counter abbb counter bcc counter b 3 c 2 a 1 intersection is the minimum of corresponding counts counter abbb counter bcc counter b 1 subtracts from an empty counter strips positive and zero counts and flips the sign on negative counts internal method to strip elements with a negative or zero count nonpositive elem for elem count in self items if not count 0 for elem in nonpositive del selfelem return self def iaddself other for elem count in other items selfelem count return self keeppositive def isubself other for elem count in other items selfelem count return self keeppositive def iorself other for elem othercount in other items count selfelem if othercount count selfelem othercount return self keeppositive def iandself other for elem count in self items othercount otherelem if othercount count selfelem othercount return self keeppositive chainmap class chainmapcollectionsabc mutablemapping def initself maps self maps listmaps or always at least one map def missingself key raise keyerrorkey def getitemself key for mapping in self maps try return mappingkey can t use key in mapping with defaultdict except keyerror pass return self missingkey support subclasses that define missing def getself key defaultnone return selfkey if key in self else default def lenself return lenset unionself maps reuses stored hash values if possible def iterself d for mapping in mapdict fromkeys reversedself maps d mapping reuses stored hash values if possible return iterd def containsself key return anykey in m for m in self maps def boolself return anyself maps recursiverepr def reprself return f self class name joinmaprepr self maps classmethod def fromkeyscls iterable args create a chainmap with a single dict created from the iterable return clsdict fromkeysiterable args def copyself new chainmap or subclass with a new copy of maps0 and refs to maps1 return self classself maps0 copy self maps1 copy copy def newchildself mnone kwargs like django s context push if m is none m kwargs elif kwargs m updatekwargs return self classm self maps property def parentsself like django s context pop new chainmap from maps1 return self classself maps1 def setitemself key value self maps0key value def delitemself key try del self maps0key except keyerror raise keyerrorf key not found in the first mapping key r def popitemself remove and return an item pair from maps0 raise keyerror is maps0 is empty try return self maps0 popitem except keyerror raise keyerror no keys found in the first mapping def popself key args remove key from maps0 and return its value raise keyerror if key not in maps0 try return self maps0 popkey args except keyerror raise keyerrorf key not found in the first mapping key r def clearself clear maps0 leaving maps1 intact self maps0 clear def iorself other self maps0 updateother return self def orself other if not isinstanceother collectionsabc mapping return notimplemented m self copy m maps0 updateother return m def rorself other if not isinstanceother collectionsabc mapping return notimplemented m dictother for child in reversedself maps m updatechild return self classm userdict class userdictcollectionsabc mutablemapping start by fillingout the abstract methods def initself dictnone kwargs self data if dict is not none self updatedict if kwargs self updatekwargs def lenself return lenself data def getitemself key if key in self data return self datakey if hasattrself class missing return self class missingself key raise keyerrorkey def setitemself key item self datakey item def delitemself key del self datakey def iterself return iterself data modify contains and get to work like dict does when missing is present def containsself key return key in self data def getself key defaultnone if key in self return selfkey return default now add the methods in dicts but not in mutablemapping def reprself return reprself data def orself other if isinstanceother userdict return self classself data other data if isinstanceother dict return self classself data other return notimplemented def rorself other if isinstanceother userdict return self classother data self data if isinstanceother dict return self classother self data return notimplemented def iorself other if isinstanceother userdict self data other data else self data other return self def copyself inst self class newself class inst dict updateself dict create a copy and avoid triggering descriptors inst dictdata self dictdata copy return inst def copyself if self class is userdict return userdictself data copy import copy data self data try self data c copy copyself finally self data data c updateself return c classmethod def fromkeyscls iterable valuenone d cls for key in iterable dkey value return d userlist class userlistcollectionsabc mutablesequence xxx should this accept an arbitrary sequence create a copy and avoid triggering descriptors userstring the following methods are defined in alphabetical order ordereddict an inherited dict maps keys to values the inherited dict provides __getitem__ __len__ __contains__ and get the remaining methods are order aware big o running times for all methods are the same as regular dictionaries the internal self __map dict maps keys to links in a doubly linked list the circular doubly linked list starts and ends with a sentinel element the sentinel element never gets deleted this simplifies the algorithm the sentinel is in self __hardroot with a weakref proxy in self __root the prev links are weakref proxies to prevent circular references individual links are kept alive by the hard reference in self __map those hard references disappear when a key is deleted from an ordereddict initialize an ordered dictionary the signature is the same as regular dictionaries keyword argument order is preserved setting a new item creates a new link at the end of the linked list and the inherited dictionary is updated with the new key value pair deleting an existing item uses self __map to find the link which gets removed by updating the links in the predecessor and successor nodes traverse the linked list in order traverse the linked list in reverse order remove and return a key value pair from the dictionary pairs are returned in lifo order if last is true or fifo order if false move an existing element to the end or beginning if last is false raise keyerror if the element does not exist number of links including root instance dictionary internal dict and inherited dict link objects proxy objects od pop k d v remove specified key and return the corresponding value if key is not found d is returned if given otherwise keyerror is raised the same as in __delitem__ insert key with a value of default if key is not in the dictionary return the value for key if key is in the dictionary else default create a new ordered dictionary with keys from iterable and values set to value od __eq__ y od y comparison to another od is order sensitive while comparison to a regular mapping is order insensitive leave the pure python version in place namedtuple returns a new subclass of tuple with named fields point namedtuple point x y point __doc__ docstring for the new class point x y p point 11 y 22 instantiate with positional args or keywords p 0 p 1 indexable like a plain tuple 33 x y p unpack like a regular tuple x y 11 22 p x p y fields also accessible by name 33 d p _asdict convert to a dictionary d x 11 point d convert from a dictionary point x 11 y 22 p _replace x 100 _replace is like str replace but targets named fields point x 100 y 22 validate the field names at the user s option either generate an error message or automatically replace the field name with a valid name variables used in the methods and docstrings create all the named tuple methods to be added to the class namespace modify function metadata to help with introspection and debugging build up the class namespace dictionary and use type to build the result class for pickling to work the __module__ variable needs to be set to the frame where the named tuple is created bypass this step in environments where sys _getframe is not defined jython for example or sys _getframe is not defined for arguments greater than 0 ironpython or where the user has specified a particular module counter load c helper function if available dict subclass for counting hashable items sometimes called a bag or multiset elements are stored as dictionary keys and their counts are stored as dictionary values c counter abcdeabcdabcaba count elements from a string c most_common 3 three most common elements a 5 b 4 c 3 sorted c list all unique elements a b c d e join sorted c elements list elements with repetitions aaaaabbbbcccdde sum c values total of all counts 15 c a count of letter a 5 for elem in shazam update counts from an iterable c elem 1 by adding 1 to each element s count c a now there are seven a 7 del c b remove all b c b now there are zero b 0 d counter simsalabim make another counter c update d add in the second counter c a now there are nine a 9 c clear empty the counter c counter note if a count is set to zero or reduced to zero it will remain in the counter until the entry is deleted or the counter is cleared c counter aaabbc c b 2 reduce the count of b by two c most_common b is still in but its count is zero a 3 c 1 b 0 references http en wikipedia org wiki multiset http www gnu org software smalltalk manual base html_node bag html http www demo2s com tutorial cpp 0380__set multiset catalog0380__set multiset htm http code activestate com recipes 259174 knuth taocp vol ii section 4 6 3 create a new empty counter object and if given count elements from an input iterable or initialize the count from another mapping of elements to their counts c counter a new empty counter c counter gallahad a new counter from an iterable c counter a 4 b 2 a new counter from a mapping c counter a 4 b 2 a new counter from keyword args needed so that self missing_item does not raise keyerror list the n most common elements and their counts from the most common to the least if n is none then list all element counts counter abracadabra most_common 3 a 5 b 2 r 2 emulate bag sortedbycount from smalltalk lazy import to speedup python startup time iterator over elements repeating each as many times as its count c counter abcabc sorted c elements a a b b c c knuth s example for prime factors of 1836 2 2 3 3 17 1 import math prime_factors counter 2 2 3 3 17 1 math prod prime_factors elements 1836 note if an element s count has been set to zero or is a negative number elements will ignore it emulate bag do from smalltalk and multiset begin from c override dict methods where necessary there is no equivalent method for counters because the semantics would be ambiguous in cases such as counter fromkeys aaabbc v 2 initializing counters to zero values isn t necessary because zero is already the default value for counter lookups initializing to one is easily accomplished with counter set iterable for more exotic cases create a dictionary first using a dictionary comprehension or dict fromkeys like dict update but add counts instead of replacing them source can be an iterable a dictionary or another counter instance c counter which c update witch add elements from another iterable d counter watch c update d add elements from another counter c h four h in which witch and watch 4 the regular dict update operation makes no sense here because the replace behavior results in the some of original untouched counts being mixed in with all of the other counts for a mismash that doesn t have a straight forward interpretation in most counting contexts instead we implement straight addition both the inputs and outputs are allowed to contain zero and negative counts fast path when counter is empty like dict update but subtracts counts instead of replacing them counts can be reduced below zero both the inputs and outputs are allowed to contain zero and negative counts source can be an iterable a dictionary or another counter instance c counter which c subtract witch subtract elements from another iterable c subtract counter watch subtract elements from another counter c h 2 in which minus 1 in witch minus 1 in watch 0 c w 1 in which minus 1 in witch minus 1 in watch 1 dict preserves the ordering returned by most_common handle case where values are not orderable multiset style mathematical operations discussed in knuth taocp volume ii section 4 6 3 exercise 19 and at http en wikipedia org wiki multiset outputs guaranteed to only include positive counts to strip negative and zero counts add in an empty counter c counter results are ordered according to when an element is first encountered in the left operand and then by the order encountered in the right operand when the multiplicities are all zero or one multiset operations are guaranteed to be equivalent to the corresponding operations for regular sets given counter multisets such as cp counter a 1 b 0 c 1 cq counter c 1 d 0 e 1 the corresponding regular sets would be sp a c sq c e all of the following relations would hold set cp cq sp sq set cp cq sp sq set cp cq sp sq set cp cq sp sq cp cq sp sq cp cq sp sq cp cq sp sq cp cq sp sq cp cq sp sq cp cq sp sq add counts from two counters counter abbb counter bcc counter b 4 c 2 a 1 subtract count but keep only results with positive counts counter abbbc counter bccd counter b 2 a 1 union is the maximum of value in either of the input counters counter abbb counter bcc counter b 3 c 2 a 1 intersection is the minimum of corresponding counts counter abbb counter bcc counter b 1 subtracts from an empty counter strips positive and zero counts and flips the sign on negative counts internal method to strip elements with a negative or zero count inplace add from another counter keeping only positive counts c counter abbb c counter bcc c counter b 4 c 2 a 1 inplace subtract counter but keep only results with positive counts c counter abbbc c counter bccd c counter b 2 a 1 inplace union is the maximum of value from either counter c counter abbb c counter bcc c counter b 3 c 2 a 1 inplace intersection is the minimum of corresponding counts c counter abbb c counter bcc c counter b 1 chainmap a chainmap groups multiple dicts or other mappings together to create a single updateable view the underlying mappings are stored in a list that list is public and can be accessed or updated using the maps attribute there is no other state lookups search the underlying mappings successively until a key is found in contrast writes updates and deletions only operate on the first mapping initialize a chainmap by setting maps to the given mappings if no mappings are provided a single empty dictionary is used always at least one map can t use key in mapping with defaultdict support subclasses that define __missing__ reuses stored hash values if possible reuses stored hash values if possible like django s context push new chainmap with a new map followed by all previous maps if no map is provided an empty dict is used keyword arguments update the map or new empty dict like django s context pop userdict start by filling out the abstract methods modify __contains__ and get to work like dict does when __missing__ is present now add the methods in dicts but not in mutablemapping create a copy and avoid triggering descriptors userlist a more or less complete user defined wrapper around list objects xxx should this accept an arbitrary sequence create a copy and avoid triggering descriptors userstring the following methods are defined in alphabetical order
__all__ = [
    'ChainMap',
    'Counter',
    'OrderedDict',
    'UserDict',
    'UserList',
    'UserString',
    'defaultdict',
    'deque',
    'namedtuple',
]

import _collections_abc
import sys as _sys

from itertools import chain as _chain
from itertools import repeat as _repeat
from itertools import starmap as _starmap
from keyword import iskeyword as _iskeyword
from operator import eq as _eq
from operator import itemgetter as _itemgetter
from reprlib import recursive_repr as _recursive_repr
from _weakref import proxy as _proxy

try:
    from _collections import deque
except ImportError:
    pass
else:
    _collections_abc.MutableSequence.register(deque)

try:
    from _collections import _deque_iterator
except ImportError:
    pass

try:
    from _collections import defaultdict
except ImportError:
    pass






class _OrderedDictKeysView(_collections_abc.KeysView):

    def __reversed__(self):
        yield from reversed(self._mapping)

class _OrderedDictItemsView(_collections_abc.ItemsView):

    def __reversed__(self):
        for key in reversed(self._mapping):
            yield (key, self._mapping[key])

class _OrderedDictValuesView(_collections_abc.ValuesView):

    def __reversed__(self):
        for key in reversed(self._mapping):
            yield self._mapping[key]

class _Link(object):
    __slots__ = 'prev', 'next', 'key', '__weakref__'

class OrderedDict(dict):
    'Dictionary that remembers insertion order'
    
    
    
    

    
    
    
    
    
    
    

    def __new__(cls, /, *args, **kwds):
        "Create the ordered dict object and set up the underlying structures."
        self = dict.__new__(cls)
        self.__hardroot = _Link()
        self.__root = root = _proxy(self.__hardroot)
        root.prev = root.next = root
        self.__map = {}
        return self

    def __init__(self, other=(), /, **kwds):
        
        self.__update(other, **kwds)

    def __setitem__(self, key, value,
                    dict_setitem=dict.__setitem__, proxy=_proxy, Link=_Link):
        'od.__setitem__(i, y) <==> od[i]=y'
        
        
        if key not in self:
            self.__map[key] = link = Link()
            root = self.__root
            last = root.prev
            link.prev, link.next, link.key = last, root, key
            last.next = link
            root.prev = proxy(link)
        dict_setitem(self, key, value)

    def __delitem__(self, key, dict_delitem=dict.__delitem__):
        'od.__delitem__(y) <==> del od[y]'
        
        
        dict_delitem(self, key)
        link = self.__map.pop(key)
        link_prev = link.prev
        link_next = link.next
        link_prev.next = link_next
        link_next.prev = link_prev
        link.prev = None
        link.next = None

    def __iter__(self):
        'od.__iter__() <==> iter(od)'
        
        root = self.__root
        curr = root.next
        while curr is not root:
            yield curr.key
            curr = curr.next

    def __reversed__(self):
        'od.__reversed__() <==> reversed(od)'
        
        root = self.__root
        curr = root.prev
        while curr is not root:
            yield curr.key
            curr = curr.prev

    def clear(self):
        'od.clear() -> None.  Remove all items from od.'
        root = self.__root
        root.prev = root.next = root
        self.__map.clear()
        dict.clear(self)

    def popitem(self, last=True):
        
        if not self:
            raise KeyError('dictionary is empty')
        root = self.__root
        if last:
            link = root.prev
            link_prev = link.prev
            link_prev.next = root
            root.prev = link_prev
        else:
            link = root.next
            link_next = link.next
            root.next = link_next
            link_next.prev = root
        key = link.key
        del self.__map[key]
        value = dict.pop(self, key)
        return key, value

    def move_to_end(self, key, last=True):
        
        link = self.__map[key]
        link_prev = link.prev
        link_next = link.next
        soft_link = link_next.prev
        link_prev.next = link_next
        link_next.prev = link_prev
        root = self.__root
        if last:
            last = root.prev
            link.prev = last
            link.next = root
            root.prev = soft_link
            last.next = link
        else:
            first = root.next
            link.prev = root
            link.next = first
            first.prev = soft_link
            root.next = link

    def __sizeof__(self):
        sizeof = _sys.getsizeof
        n = len(self) + 1                       
        size = sizeof(self.__dict__)            
        size += sizeof(self.__map) * 2          
        size += sizeof(self.__hardroot) * n     
        size += sizeof(self.__root) * n         
        return size

    update = __update = _collections_abc.MutableMapping.update

    def keys(self):
        "D.keys() -> a set-like object providing a view on D's keys"
        return _OrderedDictKeysView(self)

    def items(self):
        "D.items() -> a set-like object providing a view on D's items"
        return _OrderedDictItemsView(self)

    def values(self):
        "D.values() -> an object providing a view on D's values"
        return _OrderedDictValuesView(self)

    __ne__ = _collections_abc.MutableMapping.__ne__

    __marker = object()

    def pop(self, key, default=__marker):
        
        marker = self.__marker
        result = dict.pop(self, key, marker)
        if result is not marker:
            
            link = self.__map.pop(key)
            link_prev = link.prev
            link_next = link.next
            link_prev.next = link_next
            link_next.prev = link_prev
            link.prev = None
            link.next = None
            return result
        if default is marker:
            raise KeyError(key)
        return default

    def setdefault(self, key, default=None):
        
        if key in self:
            return self[key]
        self[key] = default
        return default

    @_recursive_repr()
    def __repr__(self):
        'od.__repr__() <==> repr(od)'
        if not self:
            return '%s()' % (self.__class__.__name__,)
        return '%s(%r)' % (self.__class__.__name__, dict(self.items()))

    def __reduce__(self):
        'Return state information for pickling'
        state = self.__getstate__()
        if state:
            if isinstance(state, tuple):
                state, slots = state
            else:
                slots = {}
            state = state.copy()
            slots = slots.copy()
            for k in vars(OrderedDict()):
                state.pop(k, None)
                slots.pop(k, None)
            if slots:
                state = state, slots
            else:
                state = state or None
        return self.__class__, (), state, None, iter(self.items())

    def copy(self):
        'od.copy() -> a shallow copy of od'
        return self.__class__(self)

    @classmethod
    def fromkeys(cls, iterable, value=None):
        
        self = cls()
        for key in iterable:
            self[key] = value
        return self

    def __eq__(self, other):
        
        if isinstance(other, OrderedDict):
            return dict.__eq__(self, other) and all(map(_eq, self, other))
        return dict.__eq__(self, other)

    def __ior__(self, other):
        self.update(other)
        return self

    def __or__(self, other):
        if not isinstance(other, dict):
            return NotImplemented
        new = self.__class__(self)
        new.update(other)
        return new

    def __ror__(self, other):
        if not isinstance(other, dict):
            return NotImplemented
        new = self.__class__(other)
        new.update(self)
        return new


try:
    from _collections import OrderedDict
except ImportError:
    
    pass






try:
    from _collections import _tuplegetter
except ImportError:
    _tuplegetter = lambda index, doc: property(_itemgetter(index), doc=doc)

def namedtuple(typename, field_names, *, rename=False, defaults=None, module=None):
    

    
    
    if isinstance(field_names, str):
        field_names = field_names.replace(',', ' ').split()
    field_names = list(map(str, field_names))
    typename = _sys.intern(str(typename))

    if rename:
        seen = set()
        for index, name in enumerate(field_names):
            if (not name.isidentifier()
                or _iskeyword(name)
                or name.startswith('_')
                or name in seen):
                field_names[index] = f'_{index}'
            seen.add(name)

    for name in [typename] + field_names:
        if type(name) is not str:
            raise TypeError('Type names and field names must be strings')
        if not name.isidentifier():
            raise ValueError('Type names and field names must be valid '
                             f'identifiers: {name!r}')
        if _iskeyword(name):
            raise ValueError('Type names and field names cannot be a '
                             f'keyword: {name!r}')

    seen = set()
    for name in field_names:
        if name.startswith('_') and not rename:
            raise ValueError('Field names cannot start with an underscore: '
                             f'{name!r}')
        if name in seen:
            raise ValueError(f'Encountered duplicate field name: {name!r}')
        seen.add(name)

    field_defaults = {}
    if defaults is not None:
        defaults = tuple(defaults)
        if len(defaults) > len(field_names):
            raise TypeError('Got more default values than field names')
        field_defaults = dict(reversed(list(zip(reversed(field_names),
                                                reversed(defaults)))))

    
    field_names = tuple(map(_sys.intern, field_names))
    num_fields = len(field_names)
    arg_list = ', '.join(field_names)
    if num_fields == 1:
        arg_list += ','
    repr_fmt = '(' + ', '.join(f'{name}=%r' for name in field_names) + ')'
    tuple_new = tuple.__new__
    _dict, _tuple, _len, _map, _zip = dict, tuple, len, map, zip

    

    namespace = {
        '_tuple_new': tuple_new,
        '__builtins__': {},
        '__name__': f'namedtuple_{typename}',
    }
    code = f'lambda _cls, {arg_list}: _tuple_new(_cls, ({arg_list}))'
    __new__ = eval(code, namespace)
    __new__.__name__ = '__new__'
    __new__.__doc__ = f'Create new instance of {typename}({arg_list})'
    if defaults is not None:
        __new__.__defaults__ = defaults

    @classmethod
    def _make(cls, iterable):
        result = tuple_new(cls, iterable)
        if _len(result) != num_fields:
            raise TypeError(f'Expected {num_fields} arguments, got {len(result)}')
        return result

    _make.__func__.__doc__ = (f'Make a new {typename} object from a sequence '
                              'or iterable')

    def _replace(self, /, **kwds):
        result = self._make(_map(kwds.pop, field_names, self))
        if kwds:
            raise ValueError(f'Got unexpected field names: {list(kwds)!r}')
        return result

    _replace.__doc__ = (f'Return a new {typename} object replacing specified '
                        'fields with new values')

    def __repr__(self):
        'Return a nicely formatted representation string'
        return self.__class__.__name__ + repr_fmt % self

    def _asdict(self):
        'Return a new dict which maps field names to their values.'
        return _dict(_zip(self._fields, self))

    def __getnewargs__(self):
        'Return self as a plain tuple.  Used by copy and pickle.'
        return _tuple(self)

    
    for method in (
        __new__,
        _make.__func__,
        _replace,
        __repr__,
        _asdict,
        __getnewargs__,
    ):
        method.__qualname__ = f'{typename}.{method.__name__}'

    
    
    class_namespace = {
        '__doc__': f'{typename}({arg_list})',
        '__slots__': (),
        '_fields': field_names,
        '_field_defaults': field_defaults,
        '__new__': __new__,
        '_make': _make,
        '__replace__': _replace,
        '_replace': _replace,
        '__repr__': __repr__,
        '_asdict': _asdict,
        '__getnewargs__': __getnewargs__,
        '__match_args__': field_names,
    }
    for index, name in enumerate(field_names):
        doc = _sys.intern(f'Alias for field number {index}')
        class_namespace[name] = _tuplegetter(index, doc)

    result = type(typename, (tuple,), class_namespace)

    
    
    
    
    
    if module is None:
        try:
            module = _sys._getframemodulename(1) or '__main__'
        except AttributeError:
            try:
                module = _sys._getframe(1).f_globals.get('__name__', '__main__')
            except (AttributeError, ValueError):
                pass
    if module is not None:
        result.__module__ = module

    return result






def _count_elements(mapping, iterable):
    'Tally elements from the iterable.'
    mapping_get = mapping.get
    for elem in iterable:
        mapping[elem] = mapping_get(elem, 0) + 1

try:                                    
    from _collections import _count_elements
except ImportError:
    pass

class Counter(dict):
    
    
    
    
    
    
    

    def __init__(self, iterable=None, /, **kwds):
        
        super().__init__()
        self.update(iterable, **kwds)

    def __missing__(self, key):
        'The count of elements not in the Counter is zero.'
        
        return 0

    def total(self):
        'Sum of the counts'
        return sum(self.values())

    def most_common(self, n=None):
        
        
        if n is None:
            return sorted(self.items(), key=_itemgetter(1), reverse=True)

        
        import heapq
        return heapq.nlargest(n, self.items(), key=_itemgetter(1))

    def elements(self):
        
        
        return _chain.from_iterable(_starmap(_repeat, self.items()))

    

    @classmethod
    def fromkeys(cls, iterable, v=None):
        
        
        
        
        
        
        
        raise NotImplementedError(
            'Counter.fromkeys() is undefined.  Use Counter(iterable) instead.')

    def update(self, iterable=None, /, **kwds):
        
        
        
        
        
        
        

        if iterable is not None:
            if isinstance(iterable, _collections_abc.Mapping):
                if self:
                    self_get = self.get
                    for elem, count in iterable.items():
                        self[elem] = count + self_get(elem, 0)
                else:
                    
                    super().update(iterable)
            else:
                _count_elements(self, iterable)
        if kwds:
            self.update(kwds)

    def subtract(self, iterable=None, /, **kwds):
        
        if iterable is not None:
            self_get = self.get
            if isinstance(iterable, _collections_abc.Mapping):
                for elem, count in iterable.items():
                    self[elem] = self_get(elem, 0) - count
            else:
                for elem in iterable:
                    self[elem] = self_get(elem, 0) - 1
        if kwds:
            self.subtract(kwds)

    def copy(self):
        'Return a shallow copy.'
        return self.__class__(self)

    def __reduce__(self):
        return self.__class__, (dict(self),)

    def __delitem__(self, elem):
        'Like dict.__delitem__() but does not raise KeyError for missing values.'
        if elem in self:
            super().__delitem__(elem)

    def __repr__(self):
        if not self:
            return f'{self.__class__.__name__}()'
        try:
            
            d = dict(self.most_common())
        except TypeError:
            
            d = dict(self)
        return f'{self.__class__.__name__}({d!r})'

    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    

    def __eq__(self, other):
        'True if all counts agree. Missing counts are treated as zero.'
        if not isinstance(other, Counter):
            return NotImplemented
        return all(self[e] == other[e] for c in (self, other) for e in c)

    def __ne__(self, other):
        'True if any counts disagree. Missing counts are treated as zero.'
        if not isinstance(other, Counter):
            return NotImplemented
        return not self == other

    def __le__(self, other):
        'True if all counts in self are a subset of those in other.'
        if not isinstance(other, Counter):
            return NotImplemented
        return all(self[e] <= other[e] for c in (self, other) for e in c)

    def __lt__(self, other):
        'True if all counts in self are a proper subset of those in other.'
        if not isinstance(other, Counter):
            return NotImplemented
        return self <= other and self != other

    def __ge__(self, other):
        'True if all counts in self are a superset of those in other.'
        if not isinstance(other, Counter):
            return NotImplemented
        return all(self[e] >= other[e] for c in (self, other) for e in c)

    def __gt__(self, other):
        'True if all counts in self are a proper superset of those in other.'
        if not isinstance(other, Counter):
            return NotImplemented
        return self >= other and self != other

    def __add__(self, other):
        
        if not isinstance(other, Counter):
            return NotImplemented
        result = Counter()
        for elem, count in self.items():
            newcount = count + other[elem]
            if newcount > 0:
                result[elem] = newcount
        for elem, count in other.items():
            if elem not in self and count > 0:
                result[elem] = count
        return result

    def __sub__(self, other):
        
        if not isinstance(other, Counter):
            return NotImplemented
        result = Counter()
        for elem, count in self.items():
            newcount = count - other[elem]
            if newcount > 0:
                result[elem] = newcount
        for elem, count in other.items():
            if elem not in self and count < 0:
                result[elem] = 0 - count
        return result

    def __or__(self, other):
        
        if not isinstance(other, Counter):
            return NotImplemented
        result = Counter()
        for elem, count in self.items():
            other_count = other[elem]
            newcount = other_count if count < other_count else count
            if newcount > 0:
                result[elem] = newcount
        for elem, count in other.items():
            if elem not in self and count > 0:
                result[elem] = count
        return result

    def __and__(self, other):
        
        if not isinstance(other, Counter):
            return NotImplemented
        result = Counter()
        for elem, count in self.items():
            other_count = other[elem]
            newcount = count if count < other_count else other_count
            if newcount > 0:
                result[elem] = newcount
        return result

    def __pos__(self):
        'Adds an empty counter, effectively stripping negative and zero counts'
        result = Counter()
        for elem, count in self.items():
            if count > 0:
                result[elem] = count
        return result

    def __neg__(self):
        
        result = Counter()
        for elem, count in self.items():
            if count < 0:
                result[elem] = 0 - count
        return result

    def _keep_positive(self):
        
        nonpositive = [elem for elem, count in self.items() if not count > 0]
        for elem in nonpositive:
            del self[elem]
        return self

    def __iadd__(self, other):
        
        for elem, count in other.items():
            self[elem] += count
        return self._keep_positive()

    def __isub__(self, other):
        
        for elem, count in other.items():
            self[elem] -= count
        return self._keep_positive()

    def __ior__(self, other):
        
        for elem, other_count in other.items():
            count = self[elem]
            if other_count > count:
                self[elem] = other_count
        return self._keep_positive()

    def __iand__(self, other):
        
        for elem, count in self.items():
            other_count = other[elem]
            if other_count < count:
                self[elem] = other_count
        return self._keep_positive()






class ChainMap(_collections_abc.MutableMapping):
    

    def __init__(self, *maps):
        
        self.maps = list(maps) or [{}]          

    def __missing__(self, key):
        raise KeyError(key)

    def __getitem__(self, key):
        for mapping in self.maps:
            try:
                return mapping[key]             
            except KeyError:
                pass
        return self.__missing__(key)            

    def get(self, key, default=None):
        return self[key] if key in self else default

    def __len__(self):
        return len(set().union(*self.maps))     

    def __iter__(self):
        d = {}
        for mapping in map(dict.fromkeys, reversed(self.maps)):
            d |= mapping                        
        return iter(d)

    def __contains__(self, key):
        return any(key in m for m in self.maps)

    def __bool__(self):
        return any(self.maps)

    @_recursive_repr()
    def __repr__(self):
        return f'{self.__class__.__name__}({", ".join(map(repr, self.maps))})'

    @classmethod
    def fromkeys(cls, iterable, *args):
        'Create a ChainMap with a single dict created from the iterable.'
        return cls(dict.fromkeys(iterable, *args))

    def copy(self):
        'New ChainMap or subclass with a new copy of maps[0] and refs to maps[1:]'
        return self.__class__(self.maps[0].copy(), *self.maps[1:])

    __copy__ = copy

    def new_child(self, m=None, **kwargs):      
        
        if m is None:
            m = kwargs
        elif kwargs:
            m.update(kwargs)
        return self.__class__(m, *self.maps)

    @property
    def parents(self):                          
        'New ChainMap from maps[1:].'
        return self.__class__(*self.maps[1:])

    def __setitem__(self, key, value):
        self.maps[0][key] = value

    def __delitem__(self, key):
        try:
            del self.maps[0][key]
        except KeyError:
            raise KeyError(f'Key not found in the first mapping: {key!r}')

    def popitem(self):
        'Remove and return an item pair from maps[0]. Raise KeyError is maps[0] is empty.'
        try:
            return self.maps[0].popitem()
        except KeyError:
            raise KeyError('No keys found in the first mapping.')

    def pop(self, key, *args):
        'Remove *key* from maps[0] and return its value. Raise KeyError if *key* not in maps[0].'
        try:
            return self.maps[0].pop(key, *args)
        except KeyError:
            raise KeyError(f'Key not found in the first mapping: {key!r}')

    def clear(self):
        'Clear maps[0], leaving maps[1:] intact.'
        self.maps[0].clear()

    def __ior__(self, other):
        self.maps[0].update(other)
        return self

    def __or__(self, other):
        if not isinstance(other, _collections_abc.Mapping):
            return NotImplemented
        m = self.copy()
        m.maps[0].update(other)
        return m

    def __ror__(self, other):
        if not isinstance(other, _collections_abc.Mapping):
            return NotImplemented
        m = dict(other)
        for child in reversed(self.maps):
            m.update(child)
        return self.__class__(m)






class UserDict(_collections_abc.MutableMapping):

    
    def __init__(self, dict=None, /, **kwargs):
        self.data = {}
        if dict is not None:
            self.update(dict)
        if kwargs:
            self.update(kwargs)

    def __len__(self):
        return len(self.data)

    def __getitem__(self, key):
        if key in self.data:
            return self.data[key]
        if hasattr(self.__class__, "__missing__"):
            return self.__class__.__missing__(self, key)
        raise KeyError(key)

    def __setitem__(self, key, item):
        self.data[key] = item

    def __delitem__(self, key):
        del self.data[key]

    def __iter__(self):
        return iter(self.data)

    
    
    def __contains__(self, key):
        return key in self.data

    def get(self, key, default=None):
        if key in self:
            return self[key]
        return default


    
    def __repr__(self):
        return repr(self.data)

    def __or__(self, other):
        if isinstance(other, UserDict):
            return self.__class__(self.data | other.data)
        if isinstance(other, dict):
            return self.__class__(self.data | other)
        return NotImplemented

    def __ror__(self, other):
        if isinstance(other, UserDict):
            return self.__class__(other.data | self.data)
        if isinstance(other, dict):
            return self.__class__(other | self.data)
        return NotImplemented

    def __ior__(self, other):
        if isinstance(other, UserDict):
            self.data |= other.data
        else:
            self.data |= other
        return self

    def __copy__(self):
        inst = self.__class__.__new__(self.__class__)
        inst.__dict__.update(self.__dict__)
        
        inst.__dict__["data"] = self.__dict__["data"].copy()
        return inst

    def copy(self):
        if self.__class__ is UserDict:
            return UserDict(self.data.copy())
        import copy
        data = self.data
        try:
            self.data = {}
            c = copy.copy(self)
        finally:
            self.data = data
        c.update(self)
        return c

    @classmethod
    def fromkeys(cls, iterable, value=None):
        d = cls()
        for key in iterable:
            d[key] = value
        return d






class UserList(_collections_abc.MutableSequence):
    

    def __init__(self, initlist=None):
        self.data = []
        if initlist is not None:
            
            if type(initlist) == type(self.data):
                self.data[:] = initlist
            elif isinstance(initlist, UserList):
                self.data[:] = initlist.data[:]
            else:
                self.data = list(initlist)

    def __repr__(self):
        return repr(self.data)

    def __lt__(self, other):
        return self.data < self.__cast(other)

    def __le__(self, other):
        return self.data <= self.__cast(other)

    def __eq__(self, other):
        return self.data == self.__cast(other)

    def __gt__(self, other):
        return self.data > self.__cast(other)

    def __ge__(self, other):
        return self.data >= self.__cast(other)

    def __cast(self, other):
        return other.data if isinstance(other, UserList) else other

    def __contains__(self, item):
        return item in self.data

    def __len__(self):
        return len(self.data)

    def __getitem__(self, i):
        if isinstance(i, slice):
            return self.__class__(self.data[i])
        else:
            return self.data[i]

    def __setitem__(self, i, item):
        self.data[i] = item

    def __delitem__(self, i):
        del self.data[i]

    def __add__(self, other):
        if isinstance(other, UserList):
            return self.__class__(self.data + other.data)
        elif isinstance(other, type(self.data)):
            return self.__class__(self.data + other)
        return self.__class__(self.data + list(other))

    def __radd__(self, other):
        if isinstance(other, UserList):
            return self.__class__(other.data + self.data)
        elif isinstance(other, type(self.data)):
            return self.__class__(other + self.data)
        return self.__class__(list(other) + self.data)

    def __iadd__(self, other):
        if isinstance(other, UserList):
            self.data += other.data
        elif isinstance(other, type(self.data)):
            self.data += other
        else:
            self.data += list(other)
        return self

    def __mul__(self, n):
        return self.__class__(self.data * n)

    __rmul__ = __mul__

    def __imul__(self, n):
        self.data *= n
        return self

    def __copy__(self):
        inst = self.__class__.__new__(self.__class__)
        inst.__dict__.update(self.__dict__)
        
        inst.__dict__["data"] = self.__dict__["data"][:]
        return inst

    def append(self, item):
        self.data.append(item)

    def insert(self, i, item):
        self.data.insert(i, item)

    def pop(self, i=-1):
        return self.data.pop(i)

    def remove(self, item):
        self.data.remove(item)

    def clear(self):
        self.data.clear()

    def copy(self):
        return self.__class__(self)

    def count(self, item):
        return self.data.count(item)

    def index(self, item, *args):
        return self.data.index(item, *args)

    def reverse(self):
        self.data.reverse()

    def sort(self, /, *args, **kwds):
        self.data.sort(*args, **kwds)

    def extend(self, other):
        if isinstance(other, UserList):
            self.data.extend(other.data)
        else:
            self.data.extend(other)






class UserString(_collections_abc.Sequence):

    def __init__(self, seq):
        if isinstance(seq, str):
            self.data = seq
        elif isinstance(seq, UserString):
            self.data = seq.data[:]
        else:
            self.data = str(seq)

    def __str__(self):
        return str(self.data)

    def __repr__(self):
        return repr(self.data)

    def __int__(self):
        return int(self.data)

    def __float__(self):
        return float(self.data)

    def __complex__(self):
        return complex(self.data)

    def __hash__(self):
        return hash(self.data)

    def __getnewargs__(self):
        return (self.data[:],)

    def __eq__(self, string):
        if isinstance(string, UserString):
            return self.data == string.data
        return self.data == string

    def __lt__(self, string):
        if isinstance(string, UserString):
            return self.data < string.data
        return self.data < string

    def __le__(self, string):
        if isinstance(string, UserString):
            return self.data <= string.data
        return self.data <= string

    def __gt__(self, string):
        if isinstance(string, UserString):
            return self.data > string.data
        return self.data > string

    def __ge__(self, string):
        if isinstance(string, UserString):
            return self.data >= string.data
        return self.data >= string

    def __contains__(self, char):
        if isinstance(char, UserString):
            char = char.data
        return char in self.data

    def __len__(self):
        return len(self.data)

    def __getitem__(self, index):
        return self.__class__(self.data[index])

    def __add__(self, other):
        if isinstance(other, UserString):
            return self.__class__(self.data + other.data)
        elif isinstance(other, str):
            return self.__class__(self.data + other)
        return self.__class__(self.data + str(other))

    def __radd__(self, other):
        if isinstance(other, str):
            return self.__class__(other + self.data)
        return self.__class__(str(other) + self.data)

    def __mul__(self, n):
        return self.__class__(self.data * n)

    __rmul__ = __mul__

    def __mod__(self, args):
        return self.__class__(self.data % args)

    def __rmod__(self, template):
        return self.__class__(str(template) % self)

    
    def capitalize(self):
        return self.__class__(self.data.capitalize())

    def casefold(self):
        return self.__class__(self.data.casefold())

    def center(self, width, *args):
        return self.__class__(self.data.center(width, *args))

    def count(self, sub, start=0, end=_sys.maxsize):
        if isinstance(sub, UserString):
            sub = sub.data
        return self.data.count(sub, start, end)

    def removeprefix(self, prefix, /):
        if isinstance(prefix, UserString):
            prefix = prefix.data
        return self.__class__(self.data.removeprefix(prefix))

    def removesuffix(self, suffix, /):
        if isinstance(suffix, UserString):
            suffix = suffix.data
        return self.__class__(self.data.removesuffix(suffix))

    def encode(self, encoding='utf-8', errors='strict'):
        encoding = 'utf-8' if encoding is None else encoding
        errors = 'strict' if errors is None else errors
        return self.data.encode(encoding, errors)

    def endswith(self, suffix, start=0, end=_sys.maxsize):
        return self.data.endswith(suffix, start, end)

    def expandtabs(self, tabsize=8):
        return self.__class__(self.data.expandtabs(tabsize))

    def find(self, sub, start=0, end=_sys.maxsize):
        if isinstance(sub, UserString):
            sub = sub.data
        return self.data.find(sub, start, end)

    def format(self, /, *args, **kwds):
        return self.data.format(*args, **kwds)

    def format_map(self, mapping):
        return self.data.format_map(mapping)

    def index(self, sub, start=0, end=_sys.maxsize):
        return self.data.index(sub, start, end)

    def isalpha(self):
        return self.data.isalpha()

    def isalnum(self):
        return self.data.isalnum()

    def isascii(self):
        return self.data.isascii()

    def isdecimal(self):
        return self.data.isdecimal()

    def isdigit(self):
        return self.data.isdigit()

    def isidentifier(self):
        return self.data.isidentifier()

    def islower(self):
        return self.data.islower()

    def isnumeric(self):
        return self.data.isnumeric()

    def isprintable(self):
        return self.data.isprintable()

    def isspace(self):
        return self.data.isspace()

    def istitle(self):
        return self.data.istitle()

    def isupper(self):
        return self.data.isupper()

    def join(self, seq):
        return self.data.join(seq)

    def ljust(self, width, *args):
        return self.__class__(self.data.ljust(width, *args))

    def lower(self):
        return self.__class__(self.data.lower())

    def lstrip(self, chars=None):
        return self.__class__(self.data.lstrip(chars))

    maketrans = str.maketrans

    def partition(self, sep):
        return self.data.partition(sep)

    def replace(self, old, new, maxsplit=-1):
        if isinstance(old, UserString):
            old = old.data
        if isinstance(new, UserString):
            new = new.data
        return self.__class__(self.data.replace(old, new, maxsplit))

    def rfind(self, sub, start=0, end=_sys.maxsize):
        if isinstance(sub, UserString):
            sub = sub.data
        return self.data.rfind(sub, start, end)

    def rindex(self, sub, start=0, end=_sys.maxsize):
        return self.data.rindex(sub, start, end)

    def rjust(self, width, *args):
        return self.__class__(self.data.rjust(width, *args))

    def rpartition(self, sep):
        return self.data.rpartition(sep)

    def rstrip(self, chars=None):
        return self.__class__(self.data.rstrip(chars))

    def split(self, sep=None, maxsplit=-1):
        return self.data.split(sep, maxsplit)

    def rsplit(self, sep=None, maxsplit=-1):
        return self.data.rsplit(sep, maxsplit)

    def splitlines(self, keepends=False):
        return self.data.splitlines(keepends)

    def startswith(self, prefix, start=0, end=_sys.maxsize):
        return self.data.startswith(prefix, start, end)

    def strip(self, chars=None):
        return self.__class__(self.data.strip(chars))

    def swapcase(self):
        return self.__class__(self.data.swapcase())

    def title(self):
        return self.__class__(self.data.title())

    def translate(self, *args):
        return self.__class__(self.data.translate(*args))

    def upper(self):
        return self.__class__(self.data.upper())

    def zfill(self, width):
        return self.__class__(self.data.zfill(width))