Coding Challenges: Professional Python
8 HackerRank-style challenges, auto-graded right in your browser
— no local install needed, standard library only. Most of
these are real, runnable logging and argparse
code, since those are genuine gradeable Python logic; a few reason
about venv/pip/packaging behavior using plain data, the same way
Chapter 28's git challenges worked, since those topics are mostly
command-line and config-file skills rather than Python logic. Write
your function in the code box, then click Run Tests
to check it against a set of test cases (including edge cases).
Stuck? Every challenge has a Show Solution reveal
at the bottom.
pip/venv behavior in a
scratch directory before being written into these tests.
1 Log Level Number to Name Easy
Write a function level_name_for_number(level_number) that returns the standard logging level name for a given numeric level, using Python's logging module. The standard mapping is: 10 → "DEBUG", 20 → "INFO", 30 → "WARNING", 40 → "ERROR", 50 → "CRITICAL".
level_number is one of 10, 20, 30, 40, 50.
level_name_for_number(30) → "WARNING"level_name_for_number(10) → "DEBUG"
Show Solution
import logging
def level_name_for_number(level_number):
return logging.getLevelName(level_number)
2 Would This Message Be Emitted? Easy
Write a function would_message_be_emitted(logger_level, message_level). A logger only emits (handles) a message if the message's numeric level is greater than or equal to the logger's configured threshold level -- e.g. a logger set to 30 (WARNING) emits a 40 (ERROR) message but suppresses a 20 (INFO) message. Return True if the message would be emitted, else False.
10, 20, 30, 40, 50.
would_message_be_emitted(30, 20) → Falsewould_message_be_emitted(30, 40) → True
Show Solution
def would_message_be_emitted(logger_level, message_level):
return message_level >= logger_level
3 Parse Real CLI Arguments Medium
Write a function parse_cli_args(argv) that builds an argparse.ArgumentParser with one required positional argument "filename", one optional flag "--verbose" (action="store_true"), and one optional flag "--output" that takes a value (default None). Parse the list argv with it and return a dict with keys "filename", "verbose", and "output" holding the parsed values.
argv is a list of strings that always includes exactly one filename and zero or more of the optional flags.
parse_cli_args(["data.csv"]) → {"filename": "data.csv", "verbose": False, "output": None}parse_cli_args(["data.csv", "--verbose"]) → {"filename": "data.csv", "verbose": True, "output": None}
Show Solution
import argparse
def parse_cli_args(argv):
parser = argparse.ArgumentParser()
parser.add_argument("filename")
parser.add_argument("--verbose", action="store_true")
parser.add_argument("--output", default=None)
ns = parser.parse_args(argv)
return {"filename": ns.filename, "verbose": ns.verbose, "output": ns.output}
4 A Count-Style Verbosity Flag Medium
Write a function count_verbosity(argv) that builds an argparse.ArgumentParser with one optional flag "--verbose" using action="count" and default=0, so passing the flag multiple times increases a count. Parse argv with it and return the resulting count as an int.
argv is a list of strings containing zero or more "--verbose" entries and nothing else.
count_verbosity([]) → 0count_verbosity(["--verbose", "--verbose"]) → 2
Show Solution
import argparse
def count_verbosity(argv):
parser = argparse.ArgumentParser()
parser.add_argument("--verbose", action="count", default=0)
ns = parser.parse_args(argv)
return ns.verbose
5 Count Emitted Messages Medium
Write a function count_emitted_messages(logger_level, message_levels). Given a logger's numeric threshold level and a list of numeric levels for messages that code attempted to log, return how many of those messages would actually be emitted (i.e. how many have a level greater than or equal to logger_level).
logger_level is an int; message_levels is a list of ints (may be empty).
count_emitted_messages(30, [10, 20, 30, 40, 50]) → 3
Show Solution
def count_emitted_messages(logger_level, message_levels):
return sum(1 for lvl in message_levels if lvl >= logger_level)
6 Classify a Dependency Pin Style Easy
Write a function dependency_pin_style(version_spec) that classifies a dependency version specifier string's pin style. Return "exact" if it contains "==", "compatible" if it contains "~=", "minimum" if it contains ">=" (and neither of the above), or "unpinned" if it's an empty string or matches none of these (no version constraint at all, just the bare package name).
version_spec is a string; check in this priority order: exact, then compatible, then minimum, else unpinned.
dependency_pin_style("==2.34.2") → "exact"dependency_pin_style("") → "unpinned"
Show Solution
def dependency_pin_style(version_spec):
if version_spec == "":
return "unpinned"
if "==" in version_spec:
return "exact"
if "~=" in version_spec:
return "compatible"
if ">=" in version_spec:
return "minimum"
return "unpinned"
7 Parse pip freeze Output Medium
Write a function parse_pip_freeze(freeze_output) that takes the multi-line string output of pip freeze (one "package==version" per line) and returns a dict mapping each package name to its version string. Ignore blank lines.
freeze_output is a string; each non-blank line has exactly one "==".
parse_pip_freeze("requests==2.34.2\nidna==3.18") → {"requests": "2.34.2", "idna": "3.18"}
Show Solution
def parse_pip_freeze(freeze_output):
result = {}
for line in freeze_output.splitlines():
line = line.strip()
if not line:
continue
name, version = line.split("==")
result[name] = version
return result
8 Build a CLI Entry-Point Line Easy
Write a function cli_entry_point_line(package_name, module_name, function_name) that returns the exact line format used inside a pyproject.toml's [project.scripts] table to register a CLI command: {package_name} = "{module_name}:{function_name}" (e.g. mycli = "mycli.cli:main").
cli_entry_point_line("mycli", "mycli.cli", "main") → 'mycli = "mycli.cli:main"'
Show Solution
def cli_entry_point_line(package_name, module_name, function_name):
return f'{package_name} = "{module_name}:{function_name}"'