Suppose we’re writing software for a clothing manufacturer. Our code accepts an array of newly produced clothing items (stored as strings) and creates text for every possible label we’ll need.
Specifically, our labels should contain the item name plus its size, ranging from 1 to 5. For example, if we have the array, ["Purple Shirt", "Green Shirt"], we want to produce label text for those shirts like this:
| | [ |
| | "Purple Shirt Size: 1", |
| | "Purple Shirt Size: 2", |
| | "Purple Shirt Size: 3", |
| | "Purple Shirt Size: 4", |
| | "Purple Shirt Size: 5", |
| | "Green Shirt Size: 1", |
| | "Green Shirt Size: 2", |
| | "Green Shirt Size: 3", |
| | "Green Shirt Size: 4", |
| | "Green Shirt Size: 5" |
| | ] |
Here’s code that will create this text for an entire array of clothing items:
| | def mark_inventory(clothing_items): |
| | clothing_options = [] |
| | |
| | for item in clothing_items: |
| | for size in range(1, 6): |
| | clothing_options.append(item + " Size: " + str(size)) |
| | |
| | return clothing_options |
Let’s determine this algorithm’s efficiency. The clothing_items are the primary data being processed, so N is the size of the array, clothing_items.
This code contains nested loops, so it’s tempting to declare this algorithm to be O(N2). However, we need to analyze this case a little more carefully. While code containing nested loops often is O(N2), in this case, it’s not.
Nested loops that result in O(N2) occur when each loop revolves around N. In our case, however, while our outer loop runs N times, our inner loop runs a constant five times; that is, this inner loop will always run five times no matter what N is.
So while our outer loop runs N times, the inner loop runs five times for each of the N strings. This means our algorithm runs 5N times, but this is reduced to O(N), since Big O notation ignores constants.