Count how many steps a single loop and a nested loop take for the same list. One grows with n, the other with n × n.
Python · intermediate · 7 min · 43 steps · free
def count_items(items):
steps = 0
for a in items:
steps += 1
return steps
def count_pairs(items):
steps = 0
for a in items:
for b in items:
steps += 1
return steps
data = [4, 8, 15]
print('linear:', count_items(data))
print('quadratic:', count_pairs(data))count_items(). Its body does not run yet: it runs each time the function is called.count_pairs(). Its body does not run yet: it runs each time the function is called.data is created and points to a new list: [4, 8, 15].steps is created with the value 0.a is created with the value 4.steps changes from 0 to 1.a changes from 4 to 8.steps changes from 1 to 2.a changes from 8 to 15.for a in items.steps.count_items() has finished, so its names are gone. It prints linear: 3.steps is created with the value 0.a is created with the value 4.b is created with the value 4.steps changes from 0 to 1.b changes from 4 to 8.steps changes from 1 to 2.b changes from 8 to 15.steps changes from 2 to 3.for b in items.b changes from 15 to 4.steps changes from 3 to 4.b changes from 4 to 8.steps changes from 4 to 5.b changes from 8 to 15.steps changes from 5 to 6.for b in items.a changes from 8 to 15.b changes from 15 to 4.steps changes from 6 to 7.b changes from 4 to 8.steps changes from 7 to 8.b changes from 8 to 15.steps changes from 8 to 9.for b in items.for a in items.steps.Answer: 4×. (2n)² = 4n².
Answer: O(n)