Python implements basic linear data structures
Array
Design of Array
The array design is originally based on memory allocation in form, so space must be requested in advance before use. This gives the array the following characteristics:
1. The size is fixed after the space is requested and cannot be changed (data overflow problem);
2. There is spatial continuity in the memory. , there will be no data that other programs need to call in the middle. This is a dedicated memory space for the array; A lower bound judgment will be made on the operation of the array, and there is a potential risk of out-of-bounds operations (for example, data will be written in the memory of the core part that needs to be called by the running program).
Because simple arrays rely heavily on computer hardware memory, they are not suitable for modern programming. If you want to use variable-size, hardware-independent data types, programming languages such as Java provide more advanced data structures: dynamic arrays such as ArrayList and Vector.
Strictly speaking: There is no array in the strict sense in Python.
List can be said to be an array in Python. The following code is the structure of CPython that implements List:
typedef struct { PyObject_VAR_HEAD /* Vector of pointers to list elements. list[0] is ob_item[0], etc. */ PyObject **ob_item; /* ob_item contains space for 'allocated' elements. The number * currently in use is ob_size. * Invariants: * 0 <= ob_size <= allocated * len(list) == ob_size * ob_item == NULL implies ob_size == allocated == 0 * list.sort() temporarily sets allocated to -1 to detect mutations. * * Items must normally not be NULL, except during construction when * the list is not yet visible outside the function that builds it. */ Py_ssize_t allocated; } PyListObject;
Some of the following structures will also be implemented using List.
Stack
What is a stack
Stack (English: stack), also directly called a stack, is a special type of stack in computer science. A data structure in the form of a series. Its special feature is that it can only allow adding data (English: push) and output data (English: top) at one end of the linked series or array (called the top of the stack, English: top). pop) operation. In addition, stacking can also be completed in the form of a one-dimensional array or connected series. Another relative operation mode of stacking is called queuing.
1. First in, first out, last in, first out.
2. Except for the head and tail nodes, each element has a predecessor and a successor.
Operation
It can be seen from the principle that the operations that can be performed on the stack (stack) are:
2. push(): Add an object to the stack
3. pop(): Push an object from the stack
Implementation
class my_stack(object): def __init__(self, value): self.value = value # 前驱 self.before = None # 后继 self.behind = None def __str__(self): return str(self.value) def top(stack): if isinstance(stack, my_stack): if stack.behind is not None: return top(stack.behind) else: return stack def push(stack, ele): push_ele = my_stack(ele) if isinstance(stack, my_stack): stack_top = top(stack) push_ele.before = stack_top push_ele.before.behind = push_ele else: raise Exception('不要乱扔东西进来好么') def pop(stack): if isinstance(stack, my_stack): stack_top = top(stack) if stack_top.before is not None: stack_top.before.behind = None stack_top.behind = None return stack_top else: print('已经是栈顶了')
What is a queue
is similar to a stack, the only difference is that the queue can only be dequeued at the head of the queue. So the queue is a linear table of first-in-first-out (FIFO, First-In-First-Out)
1. First-in-first-out, last-in-last-out
2. Except for the tail node, each node has a successor
3. (Optional) Except for the head node, each node has a predecessor
Operation
1. push():Enqueue
2.pop(): Dequeue
implementation
Ordinary queue
class MyQueue(): def __init__(self, value=None): self.value = value # 前驱 # self.before = None # 后继 self.behind = None def __str__(self): if self.value is not None: return str(self.value) else: return 'None' def create_queue(): """仅有队头""" return MyQueue() def last(queue): if isinstance(queue, MyQueue): if queue.behind is not None: return last(queue.behind) else: return queue def push(queue, ele): if isinstance(queue, MyQueue): last_queue = last(queue) new_queue = MyQueue(ele) last_queue.behind = new_queue def pop(queue): if queue.behind is not None: get_queue = queue.behind queue.behind = queue.behind.behind return get_queue else: print('队列里已经没有元素了') def print_queue(queue): print(queue) if queue.behind is not None: print_queue(queue.behind)
What is a linked list
Linked list is a common basis The data structure is a linear table, but it does not store data in a linear order. Instead, it stores a pointer to the next node in each node. Since it does not have to be stored in order, the linked list can achieve O(1) complexity when inserting, which is much faster than another linear list, sequential list, but finding a node or accessing a specific numbered node requires O(n) time, and the corresponding time complexity of the sequence table is O(logn) and O(1) respectively.
Using the linked list structure can overcome the shortcoming of the array linked list that the data size needs to be known in advance. The linked list structure can make full use of the computer memory space and achieve flexible dynamic memory management. However, the linked list loses the advantage of random reading of the array, and at the same time, the space overhead of the linked list is relatively large due to the increase of the pointer field of the node.
1. init(): initialization
2. insert(): insert
3. trave() : traverse
4. delete() : delete
5. find() : find
implementation
Only two-way lists are implemented here
class LinkedList(): def __init__(self, value=None): self.value = value # 前驱 self.before = None # 后继 self.behind = None def __str__(self): if self.value is not None: return str(self.value) else: return 'None' def init(): return LinkedList('HEAD') def delete(linked_list): if isinstance(linked_list, LinkedList): if linked_list.behind is not None: delete(linked_list.behind) linked_list.behind = None linked_list.before = None linked_list.value = None
The above is all the content of using Python to implement basic linear data structures. I hope this article will help everyone learn Python can help. If you have any questions, you can leave a message to discuss.

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

This tutorial demonstrates how to use Python to process the statistical concept of Zipf's law and demonstrates the efficiency of Python's reading and sorting large text files when processing the law. You may be wondering what the term Zipf distribution means. To understand this term, we first need to define Zipf's law. Don't worry, I'll try to simplify the instructions. Zipf's Law Zipf's law simply means: in a large natural language corpus, the most frequently occurring words appear about twice as frequently as the second frequent words, three times as the third frequent words, four times as the fourth frequent words, and so on. Let's look at an example. If you look at the Brown corpus in American English, you will notice that the most frequent word is "th

Python provides a variety of ways to download files from the Internet, which can be downloaded over HTTP using the urllib package or the requests library. This tutorial will explain how to use these libraries to download files from URLs from Python. requests library requests is one of the most popular libraries in Python. It allows sending HTTP/1.1 requests without manually adding query strings to URLs or form encoding of POST data. The requests library can perform many functions, including: Add form data Add multi-part file Access Python response data Make a request head

This article explains how to use Beautiful Soup, a Python library, to parse HTML. It details common methods like find(), find_all(), select(), and get_text() for data extraction, handling of diverse HTML structures and errors, and alternatives (Sel

Dealing with noisy images is a common problem, especially with mobile phone or low-resolution camera photos. This tutorial explores image filtering techniques in Python using OpenCV to tackle this issue. Image Filtering: A Powerful Tool Image filter

PDF files are popular for their cross-platform compatibility, with content and layout consistent across operating systems, reading devices and software. However, unlike Python processing plain text files, PDF files are binary files with more complex structures and contain elements such as fonts, colors, and images. Fortunately, it is not difficult to process PDF files with Python's external modules. This article will use the PyPDF2 module to demonstrate how to open a PDF file, print a page, and extract text. For the creation and editing of PDF files, please refer to another tutorial from me. Preparation The core lies in using external module PyPDF2. First, install it using pip: pip is P

This tutorial demonstrates how to leverage Redis caching to boost the performance of Python applications, specifically within a Django framework. We'll cover Redis installation, Django configuration, and performance comparisons to highlight the bene

Natural language processing (NLP) is the automatic or semi-automatic processing of human language. NLP is closely related to linguistics and has links to research in cognitive science, psychology, physiology, and mathematics. In the computer science

This article compares TensorFlow and PyTorch for deep learning. It details the steps involved: data preparation, model building, training, evaluation, and deployment. Key differences between the frameworks, particularly regarding computational grap
