بتل کد 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

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):
    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)}")

راهنما و جواب این چالش · برگشت به درس جلسه‌ی 68: خروجی ساخت‌یافته

بیشتر بخوان: تابع در پایتون: آموزش def، پارامتر و return با مثال