JESKO GARAGE All topicsViva questions ▶ Open the practice garage

Python Modules & external packages: 11 practice problems

UNIT 2 of the free Python for AI course. Read the short theory, then solve the problems below with instant tests. Python runs in your browser.

▶ Practise Modules & external packages nowAll topics

Theory: Modules & external packages in Python

THEORY
------
* MODULE  = one .py file.  PACKAGE = a folder of modules (minilang/ is one; __init__.py marks it).
  LIBRARY = a collection of packages (NumPy, Pandas). The STANDARD LIBRARY ships with Python.

* IMPORT FORMS
      import math                      math.sqrt(16)
      import numpy as np               alias
      from math import pi, sqrt        use names directly: sqrt(16)
      from math import *               imports everything — avoid (name clashes, unclear origin)
  Python searches sys.path: the script's folder first, then installed packages.
  Name your file random.py and `import random` imports YOUR file — classic bug!
  A module's code runs ONCE on first import (then it's cached in sys.modules).

* if __name__ == "__main__":   — this block runs only when the file is executed directly,
  not when it's imported by another file (lets a module be both a library and a script).

* STANDARD LIBRARY TOUR (know one example each)
      math         sqrt, ceil, floor, pi, e, factorial, gcd, lcm, hypot, log, isclose
      random       random(), randint(a, b), choice, shuffle, sample, seed(n) -> reproducible
      datetime     date(2024, 1, 31), datetime.now(), timedelta(days=7), strptime / strftime
      time         time(), sleep(s), perf_counter() for timing code
      os / os.path getcwd, listdir, path.join, path.exists, path.splitext, makedirs
      sys          argv, path, version, exit
      collections  Counter, defaultdict, deque, namedtuple
      statistics   mean, median, mode, stdev
      json / csv   data formats        re  regular expressions     itertools  combinations ...

* PIP — Python's package installer (downloads from PyPI, the Python Package Index)
      pip install requests              pip install numpy==1.26.4  (exact version)
      pip install --upgrade pandas      pip uninstall requests      pip list      pip show numpy
      pip freeze > requirements.txt     pip install -r requirements.txt   (reproduce an environment)
      python -m pip install x           (safest: uses the pip of THAT python)
  VIRTUAL ENVIRONMENT: isolated packages per project:
      python -m venv .venv     then activate:  .venv\Scripts\activate (Windows) / source .venv/bin/activate

11 Modules & external packages practice problems

1. When Do Two Buses Meet Again? — math.lcm / math.gcd

Easy3 ways to solve
📤 OUTPUT: return an int, e.g. 36. Use `return`, not print().
Real world: Bus A every 12 min, bus B every 18 min, both leave now. Minutes until they leave together?
    bus_sync(12, 18) -> 36
Solve “When Do Two Buses Meet Again? — math.lcm / math.gcd” in your browser →

2. Days Between Two Dates — datetime

Easy2 ways to solve
📤 OUTPUT: return an int, e.g. 60. Use `return`, not print().
Dates as "YYYY-MM-DD". Return the absolute number of days.
    days_between("2024-01-01", "2024-03-01") -> 60     (2024 is a leap year)
Hint: datetime.date.fromisoformat(...) or datetime.strptime(s, "%Y-%m-%d")
Solve “Days Between Two Dates — datetime” in your browser →

3. Age in Completed Years — datetime + logic

Medium1 way to solve
📤 OUTPUT: return an int, e.g. 23. Use `return`, not print().
    age_on("2000-08-15", "2024-08-14") -> 23     age_on("2000-08-15", "2024-08-15") -> 24
Solve “Age in Completed Years — datetime + logic” in your browser →

4. Reproducible Dice Rolls — random + seed

Easy2 ways to solve
📤 OUTPUT: return a list of n random ints between 1 and 6 (inclusive). The same seed must give the same list. Use `return`, not print().
Real world: Games and ML experiments use a SEED so results can be reproduced.
Return a list of n random ints between 1 and 6 (inclusive). The same seed must give the same list.
Hint: rng = random.Random(seed) gives an independent generator; rng.randint(1, 6)
Solve “Reproducible Dice Rolls — random + seed” in your browser →

5. Top Words — collections.Counter

Easy1 way to solve
📤 OUTPUT: return a list, e.g. [('a', 3), ('b', 2)]. Use `return`, not print().
Lower-case words split on whitespace. Return Counter.most_common(n) (a list of (word, count) tuples;
ties keep first-seen order).
    top_words("a b a c b a", 2) -> [("a", 3), ("b", 2)]
Solve “Top Words — collections.Counter” in your browser →

6. Quick Statistics — statistics module

Easy1 way to solve
📤 OUTPUT: return a dict, e.g. {'mean': 3.0, 'median': 2, 'mode': 2}. Use `return`, not print().
Return a dict {"mean": ..., "median": ..., "mode": ...} (mean rounded to 2).
    summary_stats([1, 2, 2, 3, 7]) -> {"mean": 3.0, "median": 2, "mode": 2}
Solve “Quick Statistics — statistics module” in your browser →

7. File Type From Name — os.path.splitext

Easy2 ways to solve
📤 OUTPUT: return a str (text), e.g. 'pdf'. Use `return`, not print().
Return the extension lower-cased WITHOUT the dot, or "" if none.
    file_extension("report.FINAL.PDF") -> "pdf"     file_extension("README") -> ""
Solve “File Type From Name — os.path.splitext” in your browser →

8. Build a pip Command — know pip syntax for the viva

Easy2 ways to solve
📤 OUTPUT: return a str (text), e.g. 'pip install numpy'. Use `return`, not print().
    pip_command("numpy")                -> "pip install numpy"
    pip_command("numpy", "1.26.4")      -> "pip install numpy==1.26.4"
    pip_command("pandas", upgrade=True) -> "pip install --upgrade pandas"
Solve “Build a pip Command — know pip syntax for the viva” in your browser →

9. Benchmark a Function — time.perf_counter

Medium1 way to solve
📤 OUTPUT: return a tuple (result, seconds_taken), e.g. (6, 0.0000012). Use `return`, not print().
Run func(*args) once; return a tuple (result, seconds_taken) where seconds_taken is a float >= 0.
    time_it(sum, [1, 2, 3]) -> (6, 0.0000012...)
Solve “Benchmark a Function — time.perf_counter” in your browser →

10. Incident Summary for the On-Call Engineer — interview at a cloud company

Project1 way to solve
📤 OUTPUT: return a dict, e.g. {'per_level': {'INFO': 1, 'ERROR': 3, 'WARN': …. Use `return`, not print().
Interviewer: "At 3 a.m. nobody reads raw logs. Summarise them." Use datetime and collections.Counter.
Each line: "<ISO timestamp> <LEVEL> <message>"
Return {"per_level": {level: count}, "errors": number of ERROR lines,
        "top_error": most common ERROR message (ties -> first seen) or None,
        "first": earliest timestamp, "last": latest timestamp (as the original strings),
        "duration_s": whole seconds between them}
Solve “Incident Summary for the On-Call Engineer — interview at a cloud company” in your browser →

11. Stage 12 — Build Cache Key with hashlib (why `make`/pip don't rebuild unchanged code)

Compiler1 way to solve
📤 OUTPUT: return the first 12 hex characters of hashlib.sha256(normalised.encode("utf-8")).hexdigest(). Use `return`, not print().
    Normalise: remove comments (from # to end of line), strip each line, drop empty lines, join with "
".
    Return the first 12 hex characters of hashlib.sha256(normalised.encode("utf-8")).hexdigest().
Solve “Stage 12 — Build Cache Key with hashlib (why `make`/pip don't rebuild unchanged code)” in your browser →

← Functions & scope FILE HANDLING (text & CSV) and ERROR HANDLING →