File size: 2,423 Bytes
c14504c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
{
  "task_id": "task_004_scope_bug",
  "difficulty": "medium",
  "description": "Fix the bug in make_counters. It should return a list of n functions where the i-th function returns i. Currently all returned functions return the same value (n-1) because the closure captures the loop variable by reference.",
  "buggy_code": "def make_counters(n):\n    counters = []\n    for i in range(n):\n        def counter():\n            return i\n        counters.append(counter)\n    return counters\n",
  "solution": "def make_counters(n):\n    counters = []\n    for i in range(n):\n        def counter(i=i):\n            return i\n        counters.append(counter)\n    return counters\n",
  "test_descriptions": [
    "make_counters(3) should return functions that return 0, 1, 2 respectively",
    "make_counters(1) should return a single function that returns 0",
    "make_counters(5)[4]() should return 4",
    "make_counters(0) should return an empty list"
  ],
  "test_code": "try:\n    fns = make_counters(3)\n    vals = [f() for f in fns]\n    results.append({\"test_name\": \"counters_3\", \"passed\": vals == [0, 1, 2], \"expected\": \"[0, 1, 2]\", \"actual\": str(vals), \"error\": \"\"})\nexcept Exception as e:\n    results.append({\"test_name\": \"counters_3\", \"passed\": False, \"expected\": \"[0, 1, 2]\", \"actual\": \"\", \"error\": str(e)})\n\ntry:\n    fns = make_counters(1)\n    vals = [f() for f in fns]\n    results.append({\"test_name\": \"counters_1\", \"passed\": vals == [0], \"expected\": \"[0]\", \"actual\": str(vals), \"error\": \"\"})\nexcept Exception as e:\n    results.append({\"test_name\": \"counters_1\", \"passed\": False, \"expected\": \"[0]\", \"actual\": \"\", \"error\": str(e)})\n\ntry:\n    fns = make_counters(5)\n    val = fns[4]()\n    results.append({\"test_name\": \"counter_5_last\", \"passed\": val == 4, \"expected\": \"4\", \"actual\": str(val), \"error\": \"\"})\nexcept Exception as e:\n    results.append({\"test_name\": \"counter_5_last\", \"passed\": False, \"expected\": \"4\", \"actual\": \"\", \"error\": str(e)})\n\ntry:\n    fns = make_counters(0)\n    results.append({\"test_name\": \"counters_0\", \"passed\": fns == [], \"expected\": \"[]\", \"actual\": str(fns), \"error\": \"\"})\nexcept Exception as e:\n    results.append({\"test_name\": \"counters_0\", \"passed\": False, \"expected\": \"[]\", \"actual\": \"\", \"error\": str(e)})",
  "max_steps": 7
}