Книга: A Common-Sense Guide to Data Structures and Algorithms in Python, Volume 1
Назад: Acknowledgments
Дальше: Data Structures

Chapter 1
Why Data Structures Matter

When people first learn to code, their focus is—and should be—on getting their code to run properly. Their code is measured using one simple metric: does the code actually work?

As software engineers gain more experience, though, they begin to learn about additional layers and nuances regarding the quality of their code. They learn that there can be two snippets of code that both accomplish the same task, but that one snippet is better than the other.

There are numerous measures of code quality. One important measure is code maintainability. Maintainability of code involves aspects such as the readability, organization, and modularity of one’s code.

However, another aspect of high-quality code is code efficiency. For example, you can have two code snippets that both achieve the same goal, but one runs faster than the other.

Take a look at these two functions, both of which print all the even numbers from 2 to 100:

 def​ ​print_numbers_version_one​():
  number = 2
 
 while​ number <= 100:
 # If number is even, print it:
 if​ number % 2 == 0:
 print​(number)
 
  number += 1
 def​ ​print_numbers_version_two​():
  number = 2
 
 while​ number <= 100:
 print​(number)
 
 # Increase number by 2, which, by definition,
 # is the next even number:
  number += 2

Which of these functions do you think runs faster?

If you said Version 2, you’re right. This is because Version 1 ends up looping 100 times, while Version 2 only loops 50 times. The first version then, takes twice as many steps as the second version.

This book is about writing efficient code. Having the ability to write code that runs quickly is an important aspect of becoming a better software developer.

The first step in writing fast code is to understand what data structures are and how different data structures can affect the speed of our code. So let’s dive in.

Назад: Acknowledgments
Дальше: Data Structures