עבודה נכונה עם עוזר AI לקודWorking well with an AI coding assistant
מתי לסמוך, איך לבדוק, איך לבקש, ואיך לא לאבד את ההבנה.
When to trust it, how to verify, how to ask, and how not to lose understanding.
לתקן קוד של עוזרFixing an assistant's code
תזכורת: מה ביקשוReminder: the task
הפונקציה average_rating "נכתבה על ידי עוזר" ונכשלת על ספרים בלי דירוג ועל רשימה ריקה. תקנו: מתעלמים מספרים בלי rating, ומחזירים None כשאין דירוגים.
The average_rating function was "written by an assistant" and fails on books without a rating and on an empty list. Fix it: ignore books without rating, and return None when there are no ratings.
הפתרון המלא והפלט שלוFull solution and its output
def average_rating(books):
ratings = [b["rating"] for b in books if "rating" in b]
if not ratings:
return None
return round(sum(ratings) / len(ratings), 1)
print(average_rating([{"rating": 5}, {"title": "Draft"}, {"rating": 4}]), average_rating([]))4.5 None
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
בונה בקשותA prompt builder
תזכורת: מה ביקשוReminder: the task
כתבו build_prompt(task, examples, rules) שמחזירה מחרוזת: שורה Task: ..., אחריה Examples: ושורה לכל דוגמה - <input> => <output> (עם repr), ואחריה Rules: ושורה לכל כלל - <rule>. בלי כללים: בלי שורת Rules: בכלל.
Write build_prompt(task, examples, rules) returning a string: a Task: ... line, then Examples: and a line per example - <input> => <output> (with repr), then Rules: and a line per rule - <rule>. With no rules: no Rules: line at all.
הפתרון המלא והפלט שלוFull solution and its output
def build_prompt(task, examples, rules):
lines = [f"Task: {task}", "Examples:"]
lines += [f"- {inp!r} => {out!r}" for inp, out in examples]
if rules:
lines += ["Rules:"] + [f"- {r}" for r in rules]
return "\n".join(lines)
print(build_prompt("Slugify a title", [("Hello World", "hello-world")], ["lowercase", "no punctuation"]))Task: Slugify a title Examples: - 'Hello World' => 'hello-world' Rules: - lowercase - no punctuation
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
מפרט שאפשר להריץA spec you can run
תזכורת: מה ביקשוReminder: the task
כתבו check(fn, cases) שמקבלת פונקציה ומילון קלט → פלט צפוי, ומחזירה רשימת מחרוזות "<input>: expected <want>, got <got>" לכל מקרה שנכשל (ואם הפונקציה זורקת, got הוא שם השגיאה). השתמשו בה כדי לבחור בין שתי הצעות ל-initials.
Write check(fn, cases) taking a function and a dict input → expected output, and returning strings "<input>: expected <want>, got <got>" for every failing case (if the function raises, got is the error's name). Use it to choose between two suggestions for initials.
הפתרון המלא והפלט שלוFull solution and its output
def check(fn, cases):
fails = []
for inp, want in cases.items():
try:
got = fn(inp)
except Exception as e:
got = type(e).__name__
if got != want:
fails.append(f"{inp!r}: expected {want!r}, got {got!r}")
return fails
cases = {"Frank Herbert": "F.H.", "jane austen": "J.A.", "Cher": "C.", "": ""}
suggest_a = lambda name: ".".join(w[0] for w in name.split()) + "."
suggest_b = lambda name: "".join(w[0].upper() + "." for w in name.split())
print(check(suggest_a, cases))
print(check(suggest_b, cases))["'jane austen': expected 'J.A.', got 'j.a.'", "'': expected '', got '.'"] []
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
גלאי סודותA secrets detector
תזכורת: מה ביקשוReminder: the task
כתבו find_secrets(text) שמחזירה רשימת זוגות (מספר שורה, סוג) לכל שורה שיש בה מפתח (sk- או sk_ ואחריו לפחות 12 תווים של אותיות/ספרות/-/_) או השמה של סיסמה (password בלי רגישות לאותיות, ואז = או : וערך). מספור שורות מ-1.
Write find_secrets(text) returning pairs (line number, kind) for every line holding a key (sk- or sk_ followed by at least 12 letters/digits/-/_) or a password assignment (password case-insensitive, then = or : and a value). Lines are numbered from 1.
הפתרון המלא והפלט שלוFull solution and its output
import re
KEY = re.compile(r"\bsk[-_][A-Za-z0-9_-]{12,}")
PASSWORD = re.compile(r"(?i)password\s*[:=]\s*\S+")
def find_secrets(text):
found = []
for n, line in enumerate(text.splitlines(), 1):
if KEY.search(line):
found.append((n, "key"))
if PASSWORD.search(line):
found.append((n, "password"))
return found
code = 'import os\nKEY = "sk-live_9f8e7d6c5b4a"\nDB_Password: hunter2\nprint("password reset")'
print(find_secrets(code))[(2, 'key'), (3, 'password')]
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
מדף, צעד 32: שיפור עם AI מאומת בבדיקותShelf, step 32: improving with AI, verified by tests
תזכורת: מה ביקשוReminder: the task
ביקשתם מעוזר פונקציית reading_streak(days) (days: רשימת תאריכים YYYY-MM-DD שבהם קראתם, לא ממוינת ועם כפילויות) שמחזירה את הרצף הארוך ביותר של ימים רצופים. ההצעה שקיבלתם (בקוד ההתחלה) נכשלת בבדיקות. כתבו גרסה שעוברת: ריק → 0, כפילויות נספרות פעם אחת, ומעבר חודש או שנה הוא עדיין רצף.
You asked an assistant for reading_streak(days) (days: YYYY-MM-DD dates you read on, unsorted, with duplicates) returning the longest run of consecutive days. The suggestion you got (in the starter) fails the tests. Write a version that passes: empty → 0, duplicates count once, and crossing a month or year is still a streak.
הפתרון המלא והפלט שלוFull solution and its output
from datetime import date
def reading_streak(days):
dates = sorted({date.fromisoformat(d) for d in days})
if not dates:
return 0
best = run = 1
for a, b in zip(dates, dates[1:]):
run = run + 1 if (b - a).days == 1 else 1
best = max(best, run)
return best
print(reading_streak(["2026-02-27", "2026-03-01", "2026-02-28", "2026-03-01", "2026-03-05"]))
print(reading_streak(["2025-12-31", "2026-01-01"]), reading_streak([]))3 2 0
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
שופט הצעותA suggestion judge
תזכורת: מה ביקשוReminder: the task
כתבו rank(suggestions, cases) שמקבלת מילון שם → פונקציה, ומחזירה רשימת זוגות (name, passed) ממוינת לפי מספר המקרים שעברו (מהגבוה), ובשוויון לפי שם. פונקציה שזורקת נחשבת כנכשלת במקרה הזה בלבד.
Write rank(suggestions, cases) taking a dict name → function, and returning pairs (name, passed) sorted by cases passed (highest first), and on a tie by name. A function that raises counts as failing that case only.
הפתרון המלא והפלט שלוFull solution and its output
def rank(suggestions, cases):
def passed(fn):
ok = 0
for inp, want in cases.items():
try:
ok += fn(inp) == want
except Exception:
pass
return ok
return sorted(((name, passed(fn)) for name, fn in suggestions.items()), key=lambda p: (-p[1], p[0]))
cases = {"Dune": "DUNE", " emma ": "EMMA", "": "", "Ünïcode": "ÜNÏCODE"}
suggestions = {
"upper_strip": lambda s: s.strip().upper(),
"upper_only": lambda s: s.upper(),
"ascii_only": lambda s: s.strip().encode("ascii").decode().upper(),
}
print(rank(suggestions, cases))[('upper_strip', 4), ('ascii_only', 3), ('upper_only', 3)]יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
בודק המצאותA hallucination checker
תזכורת: מה ביקשוReminder: the task
כתבו verify_calls(code) שמקבלת קוד פייתון כמחרוזת, מוצאת בעזרת המודול ast כל קריאה בצורה module.name(...) עבור המודולים math, json, random, statistics, ומחזירה רשימה ממוינת של השמות שלא קיימים במודול האמיתי (בפורמט math.cube).
Write verify_calls(code) taking Python code as a string, using the ast module to find every call of the form module.name(...) for the modules math, json, random, statistics, and returning a sorted list of names that don't exist in the real module (formatted math.cube).
הפתרון המלא והפלט שלוFull solution and its output
import ast
import importlib
CHECKED = {"math", "json", "random", "statistics"}
def verify_calls(code):
bad = set()
for node in ast.walk(ast.parse(code)):
if isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute) and isinstance(node.func.value, ast.Name):
mod, name = node.func.value.id, node.func.attr
if mod in CHECKED and not hasattr(importlib.import_module(mod), name):
bad.add(f"{mod}.{name}")
return sorted(bad)
suggested = """
import math, statistics, json
print(math.sqrt(16), math.cube(3))
print(statistics.mean([1, 2]), statistics.average([1, 2]))
data = json.loads("[1]")
json.save(data, "x.json")
"""
print(verify_calls(suggested))['json.save', 'math.cube', 'statistics.average']
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.