When a reply fails validation, programs send an error back and ask again, but only a few times.
What to build
A program that reads the replies of a simulated model and accepts the first valid one within three attempts.
Requirements
- A reply is valid when it is a JSON object whose
labelispositiveornegative. - For attempt K print
attempt K: okorattempt K: rejected (REASON). The reasons arenot JSON,not an object,missing labelandbad label. - Stop at the first valid reply. Never look at more than three replies.
- Finish with
result: LABEL, orresult: failedif no valid reply came.
Input
Line 1: n. Then n lines, the replies in order.
Output
One line per attempt, then the result line.
Constraints
1 ≤ n ≤ 10.
Example
Input:
3
Positive!
{"label": "great"}
{"label": "positive"}
Output:
attempt 1: rejected (not JSON)
attempt 2: rejected (bad label)
attempt 3: ok
result: positive
Why it works
Each rejected reply gives a specific reason that a real program would send back to the model, and the limit of three attempts makes sure the loop always ends.
Examples
3
Positive!
{"label": "great"}
{"label": "positive"}
attempt 1: rejected (not JSON) attempt 2: rejected (bad label) attempt 3: ok result: positive
1
{"label": "negative"}
attempt 1: ok result: negative
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
Loop over at most the first three replies with `enumerate(replies[:3], 1)`.
Hint 2
Work out one problem text per reply, or `None` when it is fine, then print and stop on the first fine one.
Solution
Show one correct solution (try it yourself first)
import json
n = int(input())
replies = [input() for _ in range(n)]
result = None
for attempt, reply in enumerate(replies[:3], 1):
try:
data = json.loads(reply)
except json.JSONDecodeError:
problem = "not JSON"
else:
if not isinstance(data, dict):
problem = "not an object"
elif "label" not in data:
problem = "missing label"
elif data["label"] not in ("positive", "negative"):
problem = "bad label"
else:
problem = None
if problem:
print(f"attempt {attempt}: rejected ({problem})")
else:
print(f"attempt {attempt}: ok")
result = data["label"]
break
print(f"result: {result}" if result else "result: failed")