Fun python programming (4. Introduction to data structures and algorithms)

Data structures and algorithms are very important in programming. Data structures are ways of organizing and storing data, while algorithms are methods and steps for solving problems. The Blue Bridge Cup you want to challenge is actually designing algorithms to solve problems. In fact, various programming languages ​​are just tools, and the core of the program = data structure + algorithm. Just like practicing martial arts, data structures and algorithms are internal skills, and various programming languages ​​​​are just swords, guns and sticks. Choose the weapon that is convenient for different situations according to needs.

Preface

I have browsed through various python books, and found that they are either pure knowledge point indoctrination, or there are too many pictures and game tasks for children, and the knowledge points are too trivial to make programming systematic. (It’s not that that method is bad, it’s just that the effect is limited, and it may take many years to realize it). This is also the reason why this series of tutorials has not started a line of code so far. Only by introducing the knowledge background first can subsequent learning be more effective.

Encourage in our students the habit of asking questions. Doubts are important in learning. Zhu Xi, an educator in the Ming Dynasty, said: "It is important to learn and know doubts. A small doubt will lead to small progress, and a big doubt will lead to great progress." In the learning process, it is normal and even necessary to have doubts and confusion. . There should be no worries about feeling inferior or fear of criticism. Because only when you have questions about a certain knowledge point, you will do in-depth research and find the answer, so that you can truly understand and master it. "Those who have no doubts about reading must be taught to have doubts, and those who have doubts must have no doubts. This is the only way to make progress." This quote comes from "Zhu Zi Yu Lei·Xue Wu·Reading Methods Part Two".

To learn python, you can't just learn python. You need to first understand the whole picture and fill in the background and foundation. Otherwise, it will be easy to "not know the true face of Mount Lu, just because you are in this mountain." (At least you need to catch up on the history and foundation of computers. After all, beginners are not like college students majoring in computer science. They have basic courses in operating systems, data structure algorithms and programming languages, and they can start teaching Python).

Just like writing a composition, how can I write a good composition?

If you want to write about style, you can't just write about style. You have to write about the ripples on the lake, where the clouds are going, where the flying sand is floating, the bells hanging from the eaves ringing, the ripples of boats and bamboo rafts, the corners of people's clothes and the ends of their hair that are disobedient, Write about the balloon that cannot be caught.

If you want to write about snow, you can’t just write about snow. Write about the coldness, the brightness, the vastness and sadness of all things in the world. It is necessary to write about the north wind blowing on the ground to wake up the night and the cold winter months. Write about the wax figure of Yuan Chi and the silver snake dancing in the mountains. Write about the ice forming under the bridge, and about the people walking on the street. Write about the arrogance and determination of a plum blossom, about the birds flying across thousands of mountains, and the disappearance of people on all walks. Until the end, after careful consideration, I wrote you into the words. The white heads are not separated, and the snow on the temples looks at each other.

If you want to write about the month, you can't just write about the month. To write Yin Qing, write round and missing. Write about the scars and loneliness covered by the clear light. It is necessary to write that the deer are moving in the deep forest, and the shadows are sparse and slanted. I also want to write about the strong sadness of the howling snow at night. Write a song about the loose wind of pines and the sound of piano in the mountain stream; and another about the water flowing in the water to create incense and the doors of ancient temples closing. If I put down my pen until now, I won’t mention a single word, and it will be everywhere.

If you want to write about rain, you can't just write about rain. I want to write about Bajiao and Luoxu. Write about partings and encounters that the world cannot see through. Write about the night in Bashan and the time when the plums turn yellow. Write a pile of paper about lovesickness and residual sentences. Write about the sound of dripping outside the window at dusk, as if whispering to the phoenix tree. Then I wrote that the temples in front of the steps of the monk's house are already starry, and pessimism is always ruthless. It wasn't until the end that I suddenly folded my pen and wrote you into the second half of the poem. There is only sadness left.

If you want to write about clouds, you can't just write about clouds. Write about nature and follow the wind. Write about floating and flying in the world. It is necessary to write that the clothes are beautiful and the face is beautiful, and the sill is exposed to the sun. Write about the setting sun melting gold, where are the people? Write about the bitterness and lack of proof of a deep love that will last forever. After writing this brocade book, I will stop sending it. Grief makes people sad. I miss you when I write, and I miss you at dusk. Then write about all the birds flying high and the snow falling and the smoke rising from the reeds. Until the end, Chao Sixi Ji Ti wrote that Chushan and Qinshan are all white clouds, and the director of the White Cloud Department follows you.

If you want to write about summer, you can't just write about summer. If you want to write about the heat, you should write about the chirping of cicadas. Write about the longings and encounters that the world cannot see through. I want to write about the orange breeze blowing at dusk and the wild summer night. The cicadas are chirping loudly, and the evening breeze is not cool. Full of romance and wantonness of roses. Write about the gentle breeze blowing by the river, and the bright moonlight always accompanying you. Then write about ten miles of green trees and lotus flowers, and the long summer.

If you want to write about autumn, you can’t just write about autumn. I want to write about longing and separation, the endless lovesickness and worries in this world. I want to write about going up to the west building alone and speechless, with the crescent moon like a hook. It is written that there is a faint fragrance in the sleeves, and the person is thinner than a yellow flower. Write down your expectations and demands for each month. Write about the drizzle hitting the banana trees, and write about a piece of infatuation that goes down the drain. Then write about the ancient Qinghan temple outside Gusu City, with the faint sound of bells.

If you want to learn Python, you can't just learn Python. You need to understand some computer history and basic computer knowledge. A certain computer foundation is required, including data structures, operating systems, computer networks, databases, etc. Only in this way can we better master the Python language and apply it, so that learning can be more efficient.

Introduction to data structures and algorithms

In programming, data structures and algorithms are very important. "Program = data structure + algorithm" shows the importance of data structure and algorithm. Data structure is the basis of a program, which defines how data is stored and manipulated. The algorithm is the logic and soul of the program. It defines how the program processes data to solve problems. It is important to have the concepts of data structures and algorithms at the beginning, which are very important in future programming.

Although the knowledge about data structures and algorithms alone is enough to write a book, it is still necessary to mention some. As the saying goes, "The master leads the door, and the practice lies in the individual." In fact, data structures and algorithms have been throughout the entire programming process. Sometimes you just use them and don't pay attention.

data structure

A data structure is a way of organizing data so that it can be accessed, searched, and modified efficiently. Different data structures have different performance characteristics. For example, arrays can randomly access elements, linked lists can insert and delete elements efficiently, and binary search trees can complete searches in log(n) time. Choosing the right data structure can greatly affect the efficiency and readability of your program.

Arrays, strings, lists, tuples, and dictionaries in Python that will be discussed later are actually data structures. They can be used to store and organize data, and each type has its own unique characteristics and uses. Lists and tuples are linear data structures, while dictionaries are non-linear data structures.

Linear data structure refers to a data structure in which there is a linear relationship between data elements, that is, there is a one-to-one relationship between any two data elements.

Common linear data structures include: linear list, stack, queue, double-ended queue, string (string) and linked list.​  

Nonlinear data structure refers to a data structure in which there is no linear relationship between data elements, that is, there may be a many-to-one or one-to-many relationship between any two data elements. Common nonlinear data structures include: tree, binary tree, heap, and graph.

The characteristic of linear data structure is that there is a linear relationship between elements, and data elements can be accessed or manipulated in a certain order, but insertion and deletion operations are difficult and inefficient.

The characteristic of nonlinear data structure is that there is no obvious linear relationship between elements and can represent some complex hierarchical structures and relationships. However, the order of accessing and operating data elements depends on the specific operation path, which is not intuitive enough. In some scenarios, insertion and deletion operations on non-linear data structures are more efficient.

- Array: used to store and access a collection of data elements of the same type.

- String: A data type used to store and manipulate text data.

- List: An ordered collection used to store and access data elements of any type.

- Tuple: An ordered collection used to store and access data elements of any type, but tuples are immutable.

- Dictionary: A data type used to store and access key-value pair data.

Of course you can customize the data structure! Custom data structures can be created in Python through class definitions. What is a class? What is an object? This may not be easy for beginners to understand at first, but it doesn't matter. You will naturally understand it as you use it more. Here is a brief introduction first, just to get a preliminary impression, and I will explain it later when it is used.

What is a class?

A class is an abstraction of a data structure, an abstraction of the real world. It is a model used to create objects. It defines the properties and methods of the object.

What is an object?

An object is an instance of a class and has properties and methods defined by the class. A class is a blueprint for an object, describing its characteristics and behavior. An object is a concrete instance of a class and has a concrete implementation of the characteristics and behaviors of the class.

Classes and objects are important concepts in object-oriented programming. Through classes and objects, code can be better organized and managed, improving code reusability and maintainability.

Class attributes are member variables of the class, used to store class-related information and can be used in any method of the class. Class methods are member functions of the class, which are used to define the behavior of the class and can access and modify the properties of the class. The attributes and methods of a class are the components of the class and are used to describe the characteristics and behavior of the class.

Let’s take an example of a car and talk about what a class is and what an object is:

When we talk about cars, a car is a class, which describes a class of objects with the same characteristics and behavior (a vehicle that has wheels, runs, and whistles), but you don’t know what kind of car it is, you just Know roughly what characteristics it has. But just knowing the car, you definitely can't drive it directly. You have to find a specific car entity. A specific car, such as my car, is an object of the car class. It has specific instances of the characteristics (variables such as speed, remaining fuel level) and behaviors (functions such as start, stop, and turn) defined by the class. . Classes are abstract, objects are concrete. Classes are templates for objects, and objects are instances of classes.

When we talk about animals, an animal is a class, which describes a class of objects with the same characteristics and behaviors. A specific animal, such as my pet dog, is an object of this class. It has a specific instance of the characteristics and behaviors defined by this class. Classes are abstract, objects are concrete. Classes are templates for objects, and objects are instances of classes.

In programming, what is the significance of classes and objects?

Classes and objects are important concepts in object-oriented programming. Of course, you can also do procedural programming directly without them. Some of the previous simple programming tasks basically do not involve this aspect, but in the future when you go deeper into programming, classes and objects will definitely be used.

But there are benefits to using them. They provide a good simulation of the real world and provide a way to organize and manage code. The existence of classes and objects has the following meanings:

 1. Modularization: Classes and objects can divide the program into modules, and each module has its own classes and objects, thereby reducing the complexity of the program and improving the maintainability and reusability of the code.​  

2. Abstraction: Classes and objects can abstract specific problems into abstract data types, hide internal implementation details, and expose only necessary interfaces, thereby reducing the complexity of the program and improving the readability and understandability of the code.​  

3. Encapsulation: Classes and objects can encapsulate data and functions together to form an independent unit, protecting the data from arbitrary external access and modification, thus improving the security and stability of the program.​  

4. Inheritance: Classes and objects can establish relationships between classes through inheritance, thereby realizing code sharing and reuse, reducing code redundancy, and improving code scalability and maintainability.

In short, classes and objects are important concepts in object-oriented programming. They can improve the maintainability, reusability, scalability, readability, understandability, security and stability of the code, and reduce the complexity of the program. , improve programming efficiency.

algorithm

Algorithms are also an integral part of programming, but sometimes you may not realize they exist. An algorithm is a series of explicit instructions for solving a problem or completing a specific task. The various programming tasks you do can actually be regarded as designing algorithms to solve problems.

An algorithm is a series of clear instructions for solving a problem, designed to map inputs to outputs. Algorithms are typically used to perform tasks such as computation, data processing, and automated reasoning. Algorithms can be represented in a variety of ways, including natural language, flowcharts, pseudocode, and computer programming languages. The choice of algorithm depends on the nature of the problem, the computational resources required, and the form of the target output. Some common examples of algorithms include sorting algorithms (such as bubble sort and quick sort), search algorithms (such as linear search and binary search), and encryption algorithms (such as symmetric key algorithms and public key algorithms). Algorithms can exist independently of code and can be expressed in a variety of ways, including natural language, flowcharts, pseudocode, and computer programming languages. Algorithms can exist independent of any specific programming language.

For example, if I give you a debut question, add from 1 to 100, what would you do? Your implementation could also be called a simple algorithm.

What are the common algorithms?

Common algorithms include sorting algorithms (such as bubble sort, insertion sort, quick sort), search algorithms (such as linear search, binary search), encryption algorithms (such as symmetric key algorithms, public key algorithms), shortest path algorithms (such as Dijkstra algorithm), graph algorithm (such as depth-first search algorithm, breadth-first search algorithm), etc.

Let me tell you a story about how Stanford University taught students about the binary search algorithm and then performed "tearing up the book". The lectures given by experienced foreign lecturers are vivid. Take searching for a certain word in a book as an example, and ask how to quickly find the desired word? First open half of the book, and if you can't find it, tear off half of it, and then open another half of the book in the other half to look for it until you find it. Do you think it only takes a few steps to find a word in a thick book with thousands of pages? Maybe I found it in a dozen steps, it was fast enough. This method of splitting half of the book at a time and finding a certain word from half of the book can be called an algorithm.

Summarize

Data structures and algorithms are the foundation of computer science. Understanding data structures and algorithms can help programmers better understand a program's behavior and performance, allowing them to write more efficient and maintainable code. In addition, data structures and algorithms are also core concepts in computer science and are important for writing complex software and solving real-world problems.

Other resources

Reference link

Guess you like

Origin blog.csdn.net/qq8864/article/details/134499230