بتل کد Battle Codeدارد باز می‌شود…

جواب «A Quiz as a JSON List» چالش 6 از جلسه‌ی 68

سؤال

از مدل پنج سؤال چهارگزینه‌ای به شکل لیست JSON خواسته‌ای. تابع check_question(item) را بنویس که مشکل را برگرداند یا None: اگر options لیستی با دقیقاً ۴ گزینه نیست needs 4 options؛ اگر answer عدد صحیح (int) نیست answer is not a number؛ اگر بیرون از ۰ تا ۳ است answer out of range. برنامه سؤال‌های سالم را با جواب درستشان نگه می‌دارد و بقیه را با دلیل کنار می‌گذارد. خروجی:
ok: What is 2 + 3? -> 5
skip: What is the capital of Iran? (needs 4 options)
skip: H2O is? (answer out of range)
skip: Fastest land animal? (answer is not a number)
ok: Largest planet? -> Jupiter
kept 2 of 5

راهنما

سه if به ترتیب: if not isinstance(item.get("options"), list) or len(item["options"]) != 4:، if not isinstance(item.get("answer"), int):، if not 0 <= item["answer"] < 4:. ترتیب مهم است: اول نوع، بعد بازه.

یک جواب درست

import json

reply = '''[
  {"q": "What is 2 + 3?", "options": ["4", "5", "6", "7"], "answer": 1},
  {"q": "What is the capital of Iran?", "options": ["Tabriz", "Tehran", "Shiraz"], "answer": 1},
  {"q": "H2O is?", "options": ["salt", "water", "air", "gold"], "answer": 7},
  {"q": "Fastest land animal?", "options": ["cheetah", "horse", "lion", "dog"], "answer": "0"},
  {"q": "Largest planet?", "options": ["Mars", "Venus", "Jupiter", "Earth"], "answer": 2}
]'''


def check_question(item):
    options = item.get("options")
    if not isinstance(options, list) or len(options) != 4:
        return "needs 4 options"
    answer = item.get("answer")
    if not isinstance(answer, int):
        return "answer is not a number"
    if not 0 <= answer < 4:
        return "answer out of range"
    return None


quiz = json.loads(reply)
kept = []
for item in quiz:
    problem = check_question(item)
    if problem is None:
        kept.append(item)
        print(f"ok: {item['q']} -> {item['options'][item['answer']]}")
    else:
        print(f"skip: {item['q']} ({problem})")
print(f"kept {len(kept)} of {len(quiz)}")

اول خودت امتحان کن؛ جواب‌های دیگر هم قبول است. برگرد و خودت حلش کن