Python | ネストを平坦化する練習問題セット

Python
スポンサーリンク

では、これまでの「ネスト平坦化10問」を
ターミナル(CLI)上で解ける “自動採点付きクイズアプリ” にします。

初心者でもそのまま動かせるように、
実行→回答→採点→解説 の流れが見えるようにしています。


ネスト平坦化クイズ(CLI版・自動採点付き)

# -*- coding: utf-8 -*-
"""
ネスト平坦化クイズ(自動採点付き)
-----------------------------------
・10問のネスト構造コードを表示
・ユーザーは「どう平坦化できるか」を入力
・自動で正解と照合し、スコアを表示
・途中で 'exit' で終了
"""

# ===================================
# 問題データ(問題文 + 模範解答)
# ===================================
questions = [
    {
        "id": 1,
        "question": """if x > 0:
    if x < 10:
        print("1桁の正の数です")""",
        "answer": 'if 0 < x < 10: print("1桁の正の数です")'
    },
    {
        "id": 2,
        "question": """if score >= 80:
    print("合格!")
else:
    if score >= 50:
        print("あと少し!")""",
        "answer": """if score >= 80:
    print("合格!")
elif score >= 50:
    print("あと少し!")"""
    },
    {
        "id": 3,
        "question": """if age >= 0:
    if age < 13:
        if gender == "男":
            print("少年です")""",
        "answer": 'if 0 <= age < 13 and gender == "男": print("少年です")'
    },
    {
        "id": 4,
        "question": """if temp > 0:
    if temp < 25:
        print("過ごしやすい気温です")
    else:
        print("少し暑いですね")
else:
    print("寒いです")""",
        "answer": """if temp <= 0:
    print("寒いです")
elif temp < 25:
    print("過ごしやすい気温です")
else:
    print("少し暑いですね")"""
    },
    {
        "id": 5,
        "question": """if user_input.isdigit():
    if int(user_input) > 0:
        print("正の数です")""",
        "answer": 'if user_input.isdigit() and int(user_input) > 0: print("正の数です")'
    },
    {
        "id": 6,
        "question": """if data is not None:
    if len(data) > 0:
        print("データがあります")""",
        "answer": 'if data is not None and len(data) > 0: print("データがあります")'
    },
    {
        "id": 7,
        "question": """if season == "春":
    if weather == "晴れ":
        print("お花見日和です")""",
        "answer": 'if season == "春" and weather == "晴れ": print("お花見日和です")'
    },
    {
        "id": 8,
        "question": """if not canceled:
    if paid:
        print("予約が確定しました")""",
        "answer": 'if not canceled and paid: print("予約が確定しました")'
    },
    {
        "id": 9,
        "question": """if user == "admin":
    if password == "1234":
        print("ログイン成功")
    else:
        print("パスワードが違います")
else:
    print("ユーザーが存在しません")""",
        "answer": """if user != "admin":
    print("ユーザーが存在しません")
elif password != "1234":
    print("パスワードが違います")
else:
    print("ログイン成功")"""
    },
    {
        "id": 10,
        "question": """if request:
    if request.get("user"):
        if request["user"].get("active"):
            print("アクティブなユーザーです")""",
        "answer": 'if request and "user" in request and request["user"].get("active"): print("アクティブなユーザーです")'
    }
]

# ===================================
# メイン処理
# ===================================
def main():
    print("=== 🧩 ネスト平坦化クイズ(全10問) ===")
    print("各問題で、平坦化した if文を入力してみよう!")
    print("途中で 'exit' と入力すると終了します。\n")

    score = 0

    for q in questions:
        print(f"\n--- Q{q['id']} ---")
        print("元のコード:")
        print(q["question"])
        user = input("\n▶ 平坦化したコードを入力してください(または Enter で模範解答を確認):\n> ")

        if user.lower() == "exit":
            break
        elif not user.strip():
            print("\n💡 模範解答:")
            print(q["answer"])
        elif user.replace(" ", "") == q["answer"].replace(" ", ""):
            print("✅ 正解です!")
            score += 1
        else:
            print("❌ 不正解です。")
            print("💡 模範解答:")
            print(q["answer"])

    print("\n============================")
    print(f"あなたのスコア: {score} / {len(questions)}")
    if score == len(questions):
        print("🎉 完璧です!ネスト平坦化マスター!")
    elif score >= len(questions)//2:
        print("👍 よくできました!あと少し!")
    else:
        print("💪 練習を重ねてみましょう!")

# ===================================
# 実行エントリポイント
# ===================================
if __name__ == "__main__":
    main()
Python

実行方法

  • このコードを flatten_quiz.py という名前で保存。
  • ターミナルで実行:
python flatten_quiz.py
  • 各問題で平坦化したコードを入力。
    • 空Enter → 模範解答表示
    • exit → 中断終了

特徴

機能内容
🧩 出題ネストされた if 文を10問出題
💬 ユーザー入力1行で回答(またはEnterで模範解答)
🧮 自動採点ホワイトスペース無視で比較
📊 スコア表示正答数とコメント表示
⚡️ シンプル外部ライブラリ不要、初心者OK
Python
スポンサーリンク
シェアする
@lifehackerをフォローする
スポンサーリンク
タイトルとURLをコピーしました