Loading topic
for i in range(n), which run exactly n times. Real loops rarely look that clean. They start at 1 instead of 0, stop at n - 1 or include n, skip by twos or fives, or count downward. This chapter turns any arithmetic loop (one whose control variab8 min readfor and while loops, that you can count the iterations of a single loop from its range arguments, and that you know how to add the costs of blocks that run one after another. Those topics come from the earlier chapters. Here we put one loop inside anoth7 min readn iterations around an inner loop of m iterations costs n * m steps. Second, the arithmetic series 0 + 1 + 2 + ... + (n - 1) equals n(n - 1)/2. Here you will c7 min readwhile loops, count the iterations of a loop from its bounds, and know that log2 n is the power you raise 2 to in order to get n. Earlier chapters covered loops whose control variable changes by addition, such as i += 1 or i += s. Here the control variab6 min readfloor(log2 n) + 1 iterations. You should also be comfortable summing a geometric series. Here we combine those 6 min readn, n * m, n(n-1)/2, and floor(log2 n) + 1. Exact counts are useful, but they are often more detail than you need. This chapter shows how to reduce an exact count to its order of growth, which is the part of the count that decides how th6 min readn. A loop over range(n) always ran n times, and a triangular loop always ran n(n-1)/2 times. Real code often stops early. A search returns as soon as it finds its target, and a validity check quits at the first bad 7 min readif x in items: can cost one step or a million steps, depending on what items is. This chapter shows how to fin6 min read