Detect a Stuck Agent Loop
Problem Statement
An agent stuck in a loop repeats the same action. Detect whether the last k actions in a trace are all identical, a simple no-progress guard.
Background
A cheap loop-guard fires when the most recent k actions are the same string. If the trace has fewer than k actions, it cannot yet be flagged.
Your Task
def is_stuck(actions, k):
Return True if the last k actions exist and are all equal, else False.
Input Format
- actions (list of strings), k (int, >= 1).
Output Format
- A boolean.
Sample
print(is_stuck(["a", "b", "b", "b"], 3))
Output:
True
Example
print(is_stuck(["a", "b", "b", "b"], 3))
True
- Inputs:
actionsis the agent's trace in time order, oldest first, so the most recent action is the last entry.kis the window size: how many of the newest actions must repeat before the guard fires. - Is there a full window? The trace has actions and . Since , a window of the 3 newest actions exists, so a verdict is possible.
- The window: the newest 3 actions are positions of the trace:
"b","b","b". The oldest action"a"falls outside it and plays no part. - The test: the window holds exactly one distinct value, , so every action in it is the same. The output is
True. - Notice: with the window would include
"a", giving two distinct values, so the answer would beFalse. And when there is no full window at all, which is alsoFalserather than an error.
Constraints
- Need at least
kactions to flag (else False). - The last
kmust be identical. k >= 1.