A step is a model
You choose what counts as one step. The choice must be honest, but the shape of the answer barely changes.
Library calls hide loops
A one line call like sort or sum is not free. Its cost is part of your count.
A step is one unit of work the machine does: a comparison, an add, an assignment, a lookup. Counting steps is a model, and the model only needs to be honest.
About 2 min of reading
Before this new lesson, one small question about the lesson you just finished. Recall it, do not look it up.
Count steps for lines that hide work.
Compare until found.
Before you run it, say out loud what it will print. Then open the answer.
Copy a list of 3.
Before you run it, say out loud what it will print. Then open the answer.
All pairs of 3.
Before you run it, say out loud what it will print. Then open the answer.
Append 5 items.
Before you run it, say out loud what it will print. Then open the answer.
Before you write anything, put these lines back in the right order. Click a line to move it up one step. This support step is easier than writing code from scratch, and it is here to make the last example stick.
Read the first example one line at a time. A line that prints shows what appears on screen; the rest set things up quietly.
You choose what counts as one step. The choice must be honest, but the shape of the answer barely changes.
A one line call like sort or sum is not free. Its cost is part of your count.
a = [3, 1, 2]
target = 2
steps = 0
for x in a:
steps += 1
if x == target:
break
print(steps)
Each turn does a compare. The count stops early because the loop breaks.
d = {"a": 1, "b": 2}
steps = 0
steps += 1
v = d["b"]
print(v, steps)
Reading a key from a dict is one step on average. The count does not scan the dict.
a = [1, 2, 3]
b = a[:]
print(len(b))
Slicing copies every element, so it costs n steps. A cheap looking line can hide a loop.
a = [5, 3, 1, 4]
a.sort()
print(a)
The sort is one line but it does n log n work inside. A library call still has a cost.
n = 5
a = []
for i in range(n):
a.append(i)
print(a)
Append is one step per call on average, so building costs n steps total.
a = [1, 2, 3, 4]
print(sum(a))
sum walks the whole list, so it costs n steps even though it looks like one word.
a = [4, 2, 1]
steps = 0
for i in range(len(a)):
for j in range(i + 1, len(a)):
steps += 1
print(steps)
All pairs of three items is three compares. The inner loop starts at i plus 1.
Each one is defined here on this site. Open the entry for the full definition and the other words it points at.