Python | レベル別練習問題:モジュールと import

Python
スポンサーリンク

続いては、
answers.py(模範解答+学習解説コメント付き)


modules_quiz_set/answers.py

# ================================================
# ✅ 模範解答ファイル:answers.py
# ================================================
# 各関数は quiz.py の TODO に対応しています。
# grader.py がこのファイルを参照して採点します。
# 各回答には簡単なコメントを添えています。
# ================================================

import math, random, statistics, datetime, sys, os, time, importlib
import warnings, csv, json, inspect, types
from decimal import Decimal
from fractions import Fraction
from pathlib import Path
from enum import Enum

# --- Q1〜Q10: 基礎(import構文) ---
def q1_sqrt_of_9():
    # math.sqrt() で平方根
    return math.sqrt(9)

def q2_sin_pi_over_2():
    # asエイリアス使用例
    import math as m
    return m.sin(m.pi / 2)

def q3_round_up():
    from math import ceil
    return ceil(3.2)

def q4_check_math_dir():
    return dir(math)

def q5_random_dice():
    return random.randint(1, 6)

def q6_average():
    data = [10, 20, 30]
    return statistics.mean(data)

def q7_today():
    return datetime.date.today()

def q8_sys_version():
    return sys.version

def q9_current_dir():
    return os.getcwd()

def q10_sleep_and_done():
    time.sleep(1)
    return "Done!"


# --- Q11〜Q30: 応用(自作モジュール・パッケージ) ---
def q11_use_mymath_add():
    from mymath import add
    return add(2, 3)

def q12_check_name():
    return __name__

def q13_main_check():
    if __name__ == "__main__":
        return "running directly"
    else:
        return "imported"

def q14_multi_module_calc():
    return math.sqrt(16) + random.randint(1, 3)

def q15_basename():
    return os.path.basename("/home/user/data.txt")

def q16_reload_math():
    return importlib.reload(math)

def q17_requests_import_example():
    return "import requests"

def q18_star_import_warning():
    return "Avoid using * imports"

def q19_add_path():
    sys.path.append("/my/module/path")
    return sys.path

def q20_set_env():
    os.environ["APP_MODE"] = "TEST"
    return os.environ["APP_MODE"]

def q21_package_init_explain():
    return "__init__.py makes a folder a package"

def q22_pip_install_str():
    return "pip install requests"

def q23_help_math():
    # 実際にはprint出力されるがここでは戻り値に
    return str(help(math))

def q24_alias_function():
    f = math.sqrt
    return f(25)

def q25_import_error_handling():
    try:
        import not_exist_module
    except ImportError:
        return "Import failed"

def q26_show_warning():
    warnings.warn("Be careful!")
    return "Warning shown"

def q27_factorial_5():
    return math.factorial(5)

def q28_decimal_calc():
    return Decimal('0.1') + Decimal('0.2')

def q29_fraction_add():
    return Fraction(1, 2) + Fraction(1, 3)

def q30_csv_write_example():
    return "csv.writer()"


# --- Q31〜Q50: 発展(実用・例外・構造理解) ---
def q31_use_imported_func():
    return q27_factorial_5()

def q32_sys_exit_example():
    try:
        sys.exit(0)
    except SystemExit:
        return "Exited"

def q33_shutil_copy_explain():
    return "shutil.copy('src', 'dst')"

def q34_tempfile_usage():
    return "tempfile.TemporaryFile()"

def q35_json_dumps():
    data = {"x": 1}
    return json.dumps(data)

def q36_json_loads():
    s = '{"x": 1}'
    return json.loads(s)

def q37_dynamic_import_math():
    return importlib.import_module("math")

def q38_pprint_explain():
    return "pprint.pprint() formats nested structures"

def q39_contextlib_explain():
    return "contextlib helps manage context managers"

def q40_list_files():
    return os.listdir(".")

def q41_path_example():
    return Path("data") / "file.txt"

def q42_sys_modules_explain():
    return "sys.modules stores imported modules"

def q43_import_time_explain():
    return "time.perf_counter() measures import time"

def q44_inspect_func():
    return inspect.getsource(math.sqrt)

def q45_site_explain():
    return "site manages Python environment paths"

def q46_is_function():
    return isinstance(q1_sqrt_of_9, types.FunctionType)

def q47_enum_example():
    return Enum("Color", "RED GREEN BLUE")

def q48_getsizeof_int():
    return sys.getsizeof(123)

def q49_subprocess_explain():
    return "subprocess.run(['ls']) runs shell command"

def q50_import_hook_explain():
    return "Import hooks customize how modules are loaded"
Python

このファイルは grader.py によって自動採点されます。
quiz.py の回答がこの answers.py と一致しているか比較します。

Python
スポンサーリンク
シェアする
@lifehackerをフォローする
スポンサーリンク
タイトルとURLをコピーしました