The Self-Taught Computer Scientist
Introduction to Algorithms
Download 1.48 Mb. Pdf ko'rish
|
books-library.net-11301817Az7X6
Introduction to Algorithms
6 Now, your algorithm takes 11 steps to complete. First, it assigns the variable count to zero. Then, it prints five numbers and increments five times (1 + 5 + 5 = 11). This is the new equation for your algorithm: f(n) = 11 What happens if you change the 6 in your code to a variable? count = 0 for i in range(1, n): print(i) count += i Your equation changes to this: f(n) = 1 + 2n Now the number of steps your algorithm takes depends on whatever the value of n is. The 1 in the equation represents the first step: count = 0 . Then, there are two times n steps after that. For example, if n is 5, f(n) = 1 + 2 × 5. Computer scientists call the variable n in an equation that describes the number of steps in an algorithm the size of the problem. In this case, you could say the time it takes to solve a problem of size n is 1 + 2n, or in mathematical notation, T(n) = 1 + 2n. An equation describing the number of steps in an algorithm is not very helpful, however, because, among other things, you can’t always reliably count the number of steps in an algorithm. For example, if an algorithm has many conditional statements, you have no way of knowing which of them will execute in advance. The good news is, as a computer scientist, you don’t care about the exact number of steps in an algorithm. What you want to know is how an algorithm performs as n gets bigger. Most algorithms perform fine on a small data set but may be a disaster with larger data sets. Even the most inefficient algorithm will perform well if n is 1. In the real world, however, n will probably not be 1. It may be several hundred thousand, a million, or more. The important thing to know about an algorithm is not the exact number of steps it will take but rather an approximation of the number of steps it will take as n gets bigger. As n gets larger, one part of the equation will overshadow the rest of the equation to the point that everything else becomes irrelevant. Take a look at this Python code: def print_it(n): # loop 1 for i in range(n): print(i) # loop 2 for i in range(n): |
Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling
ma'muriyatiga murojaat qiling