deque python исходный код

​​collections.deque – очередь Python

deque – коллекция двухсторонней очереди, которая похожа на список, за исключением того, что добавлять и удалять элементы можно либо в начало (слева), либо в конец (справа). Можно использовать и как стек. Реализована через двусвязный список. Благодаря этому, операции добавления или удаления элемента с любого конца deque имеют сложность O(1). Доступ к произольному элементу – O(n).

Методы

Метод append(x) – добавить элемент в конец.

Метод appendleft(x) – добавить элемент в начало.

Метод pop(x) – удалить и вернуть элемент с конца.

Метод popleft(x) – удалить и вернуть элемент с начала.

deque python исходный код. photo 2019 12 28 18.24.06. deque python исходный код фото. deque python исходный код-photo 2019 12 28 18.24.06. картинка deque python исходный код. картинка photo 2019 12 28 18.24.06. deque – коллекция двухсторонней очереди, которая похожа на список, за исключением того, что добавлять и удалять элементы можно либо в начало (слева), либо в конец (справа). Можно использовать и как стек. Реализована через двусвязный список. Благодаря этому, операции добавления или удаления элемента с любого конца deque имеют сложность O(1). Доступ к произольному элементу – O(n).

Метод clear() – очистить очередь.

Метод reverse() – развернуть очередь наоборот:

Метод rotate(n) – последовательно переносит n элементов с конца в начало (если n отрицательно, то из начала в конец):

Метод extend(iterable) – добавляет в конец все элементы iterable.

Метод extendleft(iterable) – добавляет в начало все элементы iterable (начиная с последнего элемента iterable):

Метод insert(index, x) – вставить элемент x в индекс i (медленно).

d[index] – доступ к элементу по индексу (медленно).

len(d) – число элементов в очереди (тоже работает медленно).

Метод remove(value) – удаляет первое вхождение значения value (слева направо). Остальные элементы не трогаются.

Метод count(value) – количество элементов со значением value в очереди.

Максимальная длина

Специально для канала @pyway. Подписывайтесь на мой канал в Телеграм @pyway 👈

Источник

How can I see the source code of deque module from Python’s collections library?

I tried using inspect.getsource(deque) and while it works on other modules from collections, running it on deque throws an error «could not find class definition». Why does this happen only to deque and how can I see it’s source code?

deque python исходный код. photo. deque python исходный код фото. deque python исходный код-photo. картинка deque python исходный код. картинка photo. deque – коллекция двухсторонней очереди, которая похожа на список, за исключением того, что добавлять и удалять элементы можно либо в начало (слева), либо в конец (справа). Можно использовать и как стек. Реализована через двусвязный список. Благодаря этому, операции добавления или удаления элемента с любого конца deque имеют сложность O(1). Доступ к произольному элементу – O(n).

1 Answer 1

This one is implemented in C code for CPython, and the collections python module just imports that name. Depending on your Python version and installation, you may find somewhere on your system a file called _collections.so or _collectionsmodule.so which has the real implementation, but inspect.getsource is not really smart enough to figure that out.

You can find the sources here:

deque python исходный код. leoFi. deque python исходный код фото. deque python исходный код-leoFi. картинка deque python исходный код. картинка leoFi. deque – коллекция двухсторонней очереди, которая похожа на список, за исключением того, что добавлять и удалять элементы можно либо в начало (слева), либо в конец (справа). Можно использовать и как стек. Реализована через двусвязный список. Благодаря этому, операции добавления или удаления элемента с любого конца deque имеют сложность O(1). Доступ к произольному элементу – O(n).

Not the answer you’re looking for? Browse other questions tagged python deque or ask your own question.

Related

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.9.23.40286

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

Русские Блоги

Реализация Deque и Python

Реализация Deque и Python

Deque

Реализация deque на Python

Определение типа данных deque следующее:

Примечание: направление головы и хвоста дек может быть определено в соответствии с вашими потребностями.

Приведите пример работы:

Заявление командыСодержимое стекавозвращаемое значение
d=Deque()[]
d.isEmpty[]True
d.addRear(1)[1]
d.addRear(‘a’)[ ‘a’,1]
d.addFront(‘bb’)[1, ‘a’,‘bb’]
d.addFront(55)[1, ‘a’,‘bb’,55]
d.size[1, ‘a’,‘bb’,55]4
d.removerRear[ ‘a’,‘bb’,55][1]
d.removerFront[‘a’,‘bb’][55]
d.isEmpty[‘a’,‘bb’]False

Применение Deque: решение «Палиндром»

Решить проблему «палиндрома» с двусторонними очередями несложно.
Сначала добавьте слово, которое будет оценено, в двухстороннюю очередь с конца строки
Удалите символы с обоих концов, чтобы определить, совпадают ли они, пока в двухсторонней очереди не останется 0 или 1 символ.

deque python исходный код. 88be7d524958a9ab19fa87b6dc769da9. deque python исходный код фото. deque python исходный код-88be7d524958a9ab19fa87b6dc769da9. картинка deque python исходный код. картинка 88be7d524958a9ab19fa87b6dc769da9. deque – коллекция двухсторонней очереди, которая похожа на список, за исключением того, что добавлять и удалять элементы можно либо в начало (слева), либо в конец (справа). Можно использовать и как стек. Реализована через двусвязный список. Благодаря этому, операции добавления или удаления элемента с любого конца deque имеют сложность O(1). Доступ к произольному элементу – O(n).
Процедура следующая:

Учимся у учителя Чен БиняСтруктура данных и алгоритм Версия PythonУроки

Интеллектуальная рекомендация

deque python исходный код. ea8350793a422855a146d69a78996048. deque python исходный код фото. deque python исходный код-ea8350793a422855a146d69a78996048. картинка deque python исходный код. картинка ea8350793a422855a146d69a78996048. deque – коллекция двухсторонней очереди, которая похожа на список, за исключением того, что добавлять и удалять элементы можно либо в начало (слева), либо в конец (справа). Можно использовать и как стек. Реализована через двусвязный список. Благодаря этому, операции добавления или удаления элемента с любого конца deque имеют сложность O(1). Доступ к произольному элементу – O(n).

Простой анализ таблицы фоновых данных php-wordpress

веб-сайт python или php? Если честно, php понимает, и вам нужно знать грамматику, если вы ее пишете. Создание веб-сайта на Python нужно начинать с нуля. Включая шаблоны, cms и wordpress под php. Wordp.

Источник

collections — Container datatypes¶

factory function for creating tuple subclasses with named fields

list-like container with fast appends and pops on either end

dict-like class for creating a single view of multiple mappings

dict subclass for counting hashable objects

dict subclass that remembers the order entries were added

dict subclass that calls a factory function to supply missing values

wrapper around dictionary objects for easier dict subclassing

wrapper around list objects for easier list subclassing

wrapper around string objects for easier string subclassing

Deprecated since version 3.3, will be removed in version 3.10: Moved Collections Abstract Base Classes to the collections.abc module. For backwards compatibility, they continue to be visible in this module through Python 3.9.

ChainMap objectsВ¶

A ChainMap class is provided for quickly linking a number of mappings so they can be treated as a single unit. It is often much faster than creating a new dictionary and running multiple update() calls.

The class can be used to simulate nested scopes and is useful in templating.

class collections. ChainMap ( *maps ) В¶

A ChainMap groups multiple dicts or other mappings together to create a single, updateable view. If no maps are specified, a single empty dictionary is provided so that a new chain always has at least one mapping.

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.

All of the usual dictionary methods are supported. In addition, there is a maps attribute, a method for creating new subcontexts, and a property for accessing all but the first mapping:

A user updateable list of mappings. The list is ordered from first-searched to last-searched. It is the only stored state and can be modified to change which mappings are searched. The list should always contain at least one mapping.

Changed in version 3.4: The optional m parameter was added.

Note, the iteration order of a ChainMap() is determined by scanning the mappings last to first:

This gives the same ordering as a series of dict.update() calls starting with the last mapping:

Changed in version 3.9: Added support for | and |= operators, specified in PEP 584.

The MultiContext class in the Enthought CodeTools package has options to support writing to any mapping in the chain.

Django’s Context class for templating is a read-only chain of mappings. It also features pushing and popping of contexts similar to the new_child() method and the parents property.

The Nested Contexts recipe has options to control whether writes and other mutations apply only to the first mapping or to any mapping in the chain.

ChainMap Examples and RecipesВ¶

This section shows various approaches to working with chained maps.

Example of simulating Python’s internal lookup chain:

Example of letting user specified command-line arguments take precedence over environment variables which in turn take precedence over default values:

Example patterns for using the ChainMap class to simulate nested contexts:

The ChainMap class only makes updates (writes and deletions) to the first mapping in the chain while lookups will search the full chain. However, if deep writes and deletions are desired, it is easy to make a subclass that updates keys found deeper in the chain:

Counter objectsВ¶

A counter tool is provided to support convenient and rapid tallies. For example:

A Counter is a dict subclass for counting hashable objects. It is a collection where elements are stored as dictionary keys and their counts are stored as dictionary values. Counts are allowed to be any integer value including zero or negative counts. The Counter class is similar to bags or multisets in other languages.

Elements are counted from an iterable or initialized from another mapping (or counter):

Counter objects have a dictionary interface except that they return a zero count for missing items instead of raising a KeyError :

Setting a count to zero does not remove an element from a counter. Use del to remove it entirely:

Changed in version 3.7: As a dict subclass, Counter Inherited the capability to remember insertion order. Math operations on Counter objects also preserve order. 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.

Counter objects support three methods beyond those available for all dictionaries:

Return an iterator over elements repeating each as many times as its count. Elements are returned in the order first encountered. If an element’s count is less than one, elements() will ignore it.

Elements are subtracted from an iterable or from another mapping (or counter). Like dict.update() but subtracts counts instead of replacing them. Both inputs and outputs may be zero or negative.

The usual dictionary methods are available for Counter objects except for two which work differently for counters.

This class method is not implemented for Counter objects.

Elements are counted from an iterable or added-in from another mapping (or counter). Like dict.update() but adds counts instead of replacing them. Also, the iterable is expected to be a sequence of elements, not a sequence of (key, value) pairs.

Common patterns for working with Counter objects:

Several mathematical operations are provided for combining Counter objects to produce multisets (counters that have counts greater than zero). Addition and subtraction combine counters by adding or subtracting the counts of corresponding elements. Intersection and union return the minimum and maximum of corresponding counts. Each operation can accept inputs with signed counts, but the output will exclude results with counts of zero or less.

Unary addition and subtraction are shortcuts for adding an empty counter or subtracting from an empty counter.

New in version 3.3: Added support for unary plus, unary minus, and in-place multiset operations.

Counters were primarily designed to work with positive integers to represent running counts; however, care was taken to not unnecessarily preclude use cases needing other types or negative values. To help with those use cases, this section documents the minimum range and type restrictions.

The Counter class itself is a dictionary subclass with no restrictions on its keys and values. The values are intended to be numbers representing counts, but you could store anything in the value field.

The most_common() method requires only that the values be orderable.

The multiset methods are designed only for use cases with positive values. The inputs may be negative or zero, but only outputs with positive values are created. There are no type restrictions, but the value type needs to support addition, subtraction, and comparison.

The elements() method requires integer counts. It ignores zero and negative counts.

Wikipedia entry for Multisets.

C++ multisets tutorial with examples.

For mathematical operations on multisets and their use cases, see Knuth, Donald. The Art of Computer Programming Volume II, Section 4.6.3, Exercise 19.

To enumerate all distinct multisets of a given size over a given set of elements, see itertools.combinations_with_replacement() :

deque objectsВ¶

Returns a new deque object initialized left-to-right (using append() ) with data from iterable. If iterable is not specified, the new deque is empty.

Deques are a generalization of stacks and queues (the name is pronounced “deck” and is short for “double-ended queue”). Deques support thread-safe, memory efficient appends and pops from either side of the deque with approximately the same O(1) performance in either direction.

Though list objects support similar operations, they are optimized for fast fixed-length operations and incur O(n) memory movement costs for pop(0) and insert(0, v) operations which change both the size and position of the underlying data representation.

Deque objects support the following methods:

Add x to the right side of the deque.

Add x to the left side of the deque.

Remove all elements from the deque leaving it with length 0.

Create a shallow copy of the deque.

Count the number of deque elements equal to x.

Extend the right side of the deque by appending elements from the iterable argument.

Extend the left side of the deque by appending elements from iterable. Note, the series of left appends results in reversing the order of elements in the iterable argument.

Return the position of x in the deque (at or after index start and before index stop). Returns the first match or raises ValueError if not found.

Insert x into the deque at position i.

If the insertion would cause a bounded deque to grow beyond maxlen, an IndexError is raised.

Rotate the deque n steps to the right. If n is negative, rotate to the left.

Deque objects also provide one read-only attribute:

Maximum size of a deque or None if unbounded.

deque RecipesВ¶

This section shows various approaches to working with deques.

Bounded length deques provide functionality similar to the tail filter in Unix:

Another approach to using deques is to maintain a sequence of recently added elements by appending to the right and popping to the left:

The rotate() method provides a way to implement deque slicing and deletion. For example, a pure Python implementation of del d[n] relies on the rotate() method to position elements to be popped:

defaultdict objectsВ¶

Return a new dictionary-like object. defaultdict is a subclass of the built-in dict class. It overrides one method and adds one writable instance variable. The remaining functionality is the same as for the dict class and is not documented here.

defaultdict objects support the following method in addition to the standard dict operations:

If calling default_factory raises an exception this exception is propagated unchanged.

defaultdict objects support the following instance variable:

Changed in version 3.9: Added merge ( | ) and update ( |= ) operators, specified in PEP 584.

defaultdict ExamplesВ¶

Setting the default_factory to int makes the defaultdict useful for counting (like a bag or multiset in other languages):

When a letter is first encountered, it is missing from the mapping, so the default_factory function calls int() to supply a default count of zero. The increment operation then builds up the count for each letter.

The function int() which always returns zero is just a special case of constant functions. A faster and more flexible way to create constant functions is to use a lambda function which can supply any constant value (not just zero):

Setting the default_factory to set makes the defaultdict useful for building a dictionary of sets:

namedtuple() Factory Function for Tuples with Named FieldsВ¶

Named tuples assign meaning to each position in a tuple and allow for more readable, self-documenting code. They can be used wherever regular tuples are used, and they add the ability to access fields by name instead of position index.

collections. namedtuple ( typename, field_names, *, rename=False, defaults=None, module=None ) В¶

Returns a new tuple subclass named typename. The new subclass is used to create tuple-like objects that have fields accessible by attribute lookup as well as being indexable and iterable. Instances of the subclass also have a helpful docstring (with typename and field_names) and a helpful __repr__() method which lists the tuple contents in a name=value format.

Any valid Python identifier may be used for a fieldname except for names starting with an underscore. Valid identifiers consist of letters, digits, and underscores but do not start with a digit or underscore and cannot be a keyword such as class, for, return, global, pass, or raise.

If module is defined, the __module__ attribute of the named tuple is set to that value.

Named tuple instances do not have per-instance dictionaries, so they are lightweight and require no more memory than regular tuples.

To support pickling, the named tuple class should be assigned to a variable that matches typename.

Changed in version 3.1: Added support for rename.

Changed in version 3.6: Added the module parameter.

Changed in version 3.7: Removed the verbose parameter and the _source attribute.

Changed in version 3.7: Added the defaults parameter and the _field_defaults attribute.

Named tuples are especially useful for assigning field names to result tuples returned by the csv or sqlite3 modules:

In addition to the methods inherited from tuples, named tuples support three additional methods and two attributes. To prevent conflicts with field names, the method and attribute names start with an underscore.

classmethod somenamedtuple. _make ( iterable ) В¶

Class method that makes a new instance from an existing sequence or iterable.

Return a new dict which maps field names to their corresponding values:

Return a new instance of the named tuple replacing specified fields with new values:

Tuple of strings listing the field names. Useful for introspection and for creating new named tuple types from existing named tuples.

Dictionary mapping field names to default values.

To retrieve a field whose name is stored in a string, use the getattr() function:

To convert a dictionary to a named tuple, use the double-star-operator (as described in Unpacking Argument Lists ):

Since a named tuple is a regular Python class, it is easy to add or change functionality with a subclass. Here is how to add a calculated field and a fixed-width print format:

The subclass shown above sets __slots__ to an empty tuple. This helps keep memory requirements low by preventing the creation of instance dictionaries.

Subclassing is not useful for adding new, stored fields. Instead, simply create a new named tuple type from the _fields attribute:

Docstrings can be customized by making direct assignments to the __doc__ fields:

Changed in version 3.5: Property docstrings became writeable.

See typing.NamedTuple for a way to add type hints for named tuples. It also provides an elegant notation using the class keyword:

See types.SimpleNamespace() for a mutable namespace based on an underlying dictionary instead of a tuple.

The dataclasses module provides a decorator and functions for automatically adding generated special methods to user-defined classes.

OrderedDict objectsВ¶

Ordered dictionaries are just like regular dictionaries but have some extra capabilities relating to ordering operations. They have become less important now that the built-in dict class gained the ability to remember insertion order (this new behavior became guaranteed in Python 3.7).

Some differences from dict still remain:

The regular dict was designed to be very good at mapping operations. Tracking insertion order was secondary.

The OrderedDict was designed to be good at reordering operations. Space efficiency, iteration speed, and the performance of update operations were secondary.

The equality operation for OrderedDict checks for matching order.

The popitem() method of OrderedDict has a different signature. It accepts an optional argument to specify which item is popped.

OrderedDict has a move_to_end() method to efficiently reposition an element to an endpoint.

Until Python 3.8, dict lacked a __reversed__() method.

class collections. OrderedDict ( [ items ] ) В¶

Return an instance of a dict subclass that has methods specialized for rearranging dictionary order.

The popitem() method for ordered dictionaries returns and removes a (key, value) pair. The pairs are returned in LIFO order if last is true or FIFO order if false.

move_to_end ( key, last=True ) В¶

Move an existing key to either end of an ordered dictionary. The item is moved to the right end if last is true (the default) or to the beginning if last is false. Raises KeyError if the key does not exist:

Changed in version 3.6: With the acceptance of PEP 468, order is retained for keyword arguments passed to the OrderedDict constructor and its update() method.

Changed in version 3.9: Added merge ( | ) and update ( |= ) operators, specified in PEP 584.

OrderedDict Examples and RecipesВ¶

It is straightforward to create an ordered dictionary variant that remembers the order the keys were last inserted. If a new entry overwrites an existing entry, the original insertion position is changed and moved to the end:

An OrderedDict would also be useful for implementing variants of functools.lru_cache() :

UserDict objectsВ¶

The class, UserDict acts as a wrapper around dictionary objects. The need for this class has been partially supplanted by the ability to subclass directly from dict ; however, this class can be easier to work with because the underlying dictionary is accessible as an attribute.

class collections. UserDict ( [ initialdata ] ) В¶

Class that simulates a dictionary. The instance’s contents are kept in a regular dictionary, which is accessible via the data attribute of UserDict instances. If initialdata is provided, data is initialized with its contents; note that a reference to initialdata will not be kept, allowing it to be used for other purposes.

In addition to supporting the methods and operations of mappings, UserDict instances provide the following attribute:

A real dictionary used to store the contents of the UserDict class.

UserList objectsВ¶

This class acts as a wrapper around list objects. It is a useful base class for your own list-like classes which can inherit from them and override existing methods or add new ones. In this way, one can add new behaviors to lists.

The need for this class has been partially supplanted by the ability to subclass directly from list ; however, this class can be easier to work with because the underlying list is accessible as an attribute.

class collections. UserList ( [ list ] ) В¶

In addition to supporting the methods and operations of mutable sequences, UserList instances provide the following attribute:

A real list object used to store the contents of the UserList class.

Subclassing requirements: Subclasses of UserList are expected to offer a constructor which can be called with either no arguments or one argument. List operations which return a new sequence attempt to create an instance of the actual implementation class. To do so, it assumes that the constructor can be called with a single parameter, which is a sequence object used as a data source.

If a derived class does not wish to comply with this requirement, all of the special methods supported by this class will need to be overridden; please consult the sources for information about the methods which need to be provided in that case.

UserString objectsВ¶

The class, UserString acts as a wrapper around string objects. The need for this class has been partially supplanted by the ability to subclass directly from str ; however, this class can be easier to work with because the underlying string is accessible as an attribute.

class collections. UserString ( seq ) В¶

Class that simulates a string object. The instance’s content is kept in a regular string object, which is accessible via the data attribute of UserString instances. The instance’s contents are initially set to a copy of seq. The seq argument can be any object which can be converted into a string using the built-in str() function.

In addition to supporting the methods and operations of strings, UserString instances provide the following attribute:

A real str object used to store the contents of the UserString class.

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *