PIXELBANKv9.1.0
Menu

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:

Input:
print(is_stuck(["a", "b", "b", "b"], 3))
Output:
True
Reasoning:
  • Check if the trace length is sufficient to evaluate the last kk actions: the list ["a", "b", "b", "b"] has a length of 4, which is greater than or equal to k=3k=3, so the check proceeds.
  • Extract the most recent kk actions from the end of the list: the last 3 elements are ["b", "b", "b"].
  • Verify if all actions in this subset are identical by comparing each element to the first one: "b" == "b", "b" == "b", and "b" == "b" all evaluate to true.
  • Since every action in the window matches, the condition for being stuck is satisfied.
  • The final output is True

Constraints:

  • Need at least k actions to flag (else False).
  • The last k must be identical.
  • k >= 1.
πŸ”’

Editor locked

The code editor is locked for Pro problems. It is only available for free problems. Please upgrade to gain access to the code editor for all problems.

solution.py

Test Results

0/0
Run code to see test results.