challenge-coding-004
Suite:
codingFinish:
stopPrompt
只输出 Python 代码,不要解释。实现 solve(capacity: int, ops: list[str]) -> list[int],模拟 LRU cache。ops 包含 "put key value" 和 "get key"。get 返回 value,不存在返回 -1。put 已存在 key 要更新并变成最近使用。容量为 0 时所有 get 都返回 -1。
Standard Answer / Scoring Expectation
Reference tests: ops = ['put a 1', 'put b 2', 'get a', 'put c 3', 'get b', 'get a', 'get c'] assert solution.solve(2, ops) == [1, -1, 1, 3] assert solution.solve(0, ['put a 1', 'get a']) == [-1] assert solution.solve(1, ['put a 1', 'put a 2', 'get a']) == [2]
Mistake Analysis
Failure type:
runtime_type_assumption题目里的 cache key 是字符串,例如 `a`、`b`、`c`,但模型把 key 强行写成 `int(parts[1])`。测试一遇到 `put a 1` 就在解析 `a` 时抛出 ValueError。根因是模型擅自补了“key 是整数”的类型假设。
Scorer Details
{
"returncode": 1,
"stdout": "",
"stderr": "Traceback (most recent call last):\n File \"/var/folders/x_/4cht1kfj1_j31gdv5w01sgmw0000gn/T/dracobench-code-ahvjkf0e/test_solution.py\", line 4, in <module>\n assert solution.solve(2, ops) == [1, -1, 1, 3]\n ^^^^^^^^^^^^^^^^^^^^^^\n File \"/private/var/folders/x_/4cht1kfj1_j31gdv5w01sgmw0000gn/T/dracobench-code-ahvjkf0e/solution.py\", line 14, in solve\n key = int(parts[1])\n ^^^^^^^^^^^^^\nValueError: invalid literal for int() with base 10: 'a'\n"
}
Output
```python
from collections import OrderedDict
def solve(capacity: int, ops: list[str]) -> list[int]:
cache: OrderedDict[int, int] = OrderedDict()
res: list[int] = []
if capacity <= 0:
for op in ops:
if op.startswith("get"):
res.append(-1)
return res
for op in ops:
parts = op.split()
if parts[0] == "put":
key = int(parts[1])
value = int(parts[2])
if key in cache:
cache.move_to_end(key)
elif len(cache) >= capacity:
cache.popitem(last=False)
cache[key] = value
else:
key = int(parts[1])
if key in cache:
cache.move_to_end(key)
res.append(cache[key])
else:
res.append(-1)
return res
```