runtime
233 / 500
question 233 Debugging & Logging · easy

A compact call stack

An error dashboard shows each crash's call stack on one screen. A deep recursion can produce hundreds of identical frames, so Python's own tracebacks collapse them ([Previous line repeated 996 more times]). Write compact_stack(frames) that does the same for the dashboard: one entry per frame, oldest first, with each run of identical consecutive frames shown once with a count.

Functioncompact_stack(frames)
framesa list of [file, line, function] lists, oldest call first, like traceback.extract_tb gives
Returnsa list of texts "function (file:line)"; a run of 2 or more identical consecutive frames becomes one text ending in x<count>
Identicalsame file, same line and same function; the same function on another line is a different frame
Examples
callcompact_stack([['tree.py', 30, '<module>'], ['tree.py', 12, 'depth'], ['tree.py', 12, 'depth'], ['tree.py', 12, 'depth'], ['tree.py', 9, 'depth']])returns['<module> (tree.py:30)', 'depth (tree.py:12) x3', 'depth (tree.py:9)']
callcompact_stack([['main.py', 14, '<module>'], ['main.py', 9, 'price_report'], ['main.py', 4, 'unit_price']])returns['<module> (main.py:14)', 'price_report (main.py:9)', 'unit_price (main.py:4)']
callcompact_stack([])returns[]

Loading your progress…

A compact call stack — Python practice · Runtime