16/36
Part 4 of 8 · Comparing samplesLearn and do

A frame is the same call only if every frame below it matches

Take ["main", "a", "b"] followed by ["main", "b"]:

["main", "a", "b"], then ["main", "b"]
mainab
before
mainb
after

a is gone, so this b is a new call, made by main.

The first b was called by a. The second was called by main, so it's a different call that happens to run the same function. Comparing names without their position gets this wrong:

def by_set(before, after, time):
    gone = [n for n in reversed(before) if n not in set(after)]
    new = [n for n in after if n not in set(before)]
    return [(time, "end", n) for n in gone] + [(time, "start", n) for n in new]


print(by_set(["main", "a", "b"], ["main", "b"], 1))
print(by_set(["main", "f"], ["main", "f", "f"], 3))
[(1, 'end', 'a')]
[]

The first answer should be [(1, 'end', 'b'), (1, 'end', 'a'), (1, 'start', 'b')]. Recursion breaks it worse: from ["main", "f"] to ["main", "f", "f"] a second call of f started, and by_set reports nothing. Count the shared frames by position and both come out right.

In the editor, finish events_between(before, after, time): count the shared frames, then build the ends and the starts. It's the heart of level 1 of the practice problem. There you run it over each pair of neighboring samples, starting from an empty stack, and end each open call after the last sample. That whole loop is called trace(samples).