"""
Python practice exercises, for developers coming from Java / TS / JS / PHP.

How to use:
  1. Pick an exercise, delete the `raise NotImplementedError` line and write your code.
  2. Check your progress:      uv run check.py        (or: python3 check.py)
     Check just one exercise:   uv run check.py 7
  3. Stuck? Compare with solutions.py (try first!).

Rules of thumb while solving:
  - No C-style index loops (`for i in range(len(x))`) unless there's truly no other way.
  - Prefer comprehensions, unpacking, slicing, enumerate and zip.
"""

from dataclasses import dataclass  # you'll need this in exercise 22
import math                         # and this one too


# ---------------------------------------------------------------------------
# Part 1: Lists, loops and idioms
# ---------------------------------------------------------------------------

def greet(name, times):
    """1. Return a list with "Hi <name>" repeated `times` times.

    greet("Ana", 3) -> ["Hi Ana", "Hi Ana", "Hi Ana"]
    Hint: an f-string inside a list, multiplied by a number. One line.
    """
    raise NotImplementedError


def count_positive(nums):
    """2. Count how many numbers are greater than 0.

    count_positive([3, -1, 0, 5]) -> 2
    Hint: sum() over a generator expression: sum(1 for ... if ...)
    """
    raise NotImplementedError


def squares_of_evens(nums):
    """3. Return the squares of the even numbers, in order.

    squares_of_evens([1, 2, 3, 4]) -> [4, 16]
    Hint: a list comprehension with an `if`.
    """
    raise NotImplementedError


def index_of_max(nums):
    """4. Return the index of the largest number (the first one if tied).
    Return None for an empty list.

    index_of_max([3, 9, 2, 9]) -> 1
    Hint: loop with enumerate(). (Bonus: there's also a one-liner with max(..., key=...).)
    """
    raise NotImplementedError


def pair_up(names, scores):
    """5. Combine two lists into a dict {name: score}.

    pair_up(["ana", "bo"], [90, 85]) -> {"ana": 90, "bo": 85}
    If one list is longer, the extra items are ignored.
    Hint: zip() — and dict() accepts pairs directly.
    """
    raise NotImplementedError


def first_and_rest(items):
    """6. Return a tuple (first_item, list_of_the_rest).
    For an empty list return (None, []).

    first_and_rest([1, 2, 3]) -> (1, [2, 3])
    Hint: star unpacking: first, *rest = items
    """
    raise NotImplementedError


def swap_ends(items):
    """7. Return a NEW list with the first and last items swapped.
    Don't modify the original list.

    swap_ends([1, 2, 3, 4]) -> [4, 2, 3, 1]
    Hint: copy with items[:] or list(items), then swap with a, b = b, a
    """
    raise NotImplementedError


# ---------------------------------------------------------------------------
# Part 2: Slicing
# ---------------------------------------------------------------------------

def reverse_string(s):
    """8. Reverse a string.  reverse_string("hello") -> "olleh"
    Hint: one slice.
    """
    raise NotImplementedError


def is_palindrome(s):
    """9. True if `s` reads the same backwards, ignoring case and anything
    that isn't a letter or digit.

    is_palindrome("A man, a plan, a canal: Panama") -> True
    Hint: "".join(...) a comprehension using ch.isalnum() and ch.lower().
    """
    raise NotImplementedError


def every_other(items):
    """10. Return every other item, starting with the first.

    every_other([1, 2, 3, 4, 5]) -> [1, 3, 5]
    """
    raise NotImplementedError


def last_n(items, n):
    """11. Return the last n items.

    last_n([1, 2, 3, 4, 5], 2) -> [4, 5]
    last_n([1, 2, 3], 0)       -> []      <- careful! items[-0:] is NOT empty
    """
    raise NotImplementedError


def chunk(items, size):
    """12. Split a list into chunks of `size`.

    chunk([1, 2, 3, 4, 5], 2) -> [[1, 2], [3, 4], [5]]
    Hint: a comprehension over range(0, len(items), size) plus slicing.
    """
    raise NotImplementedError


# ---------------------------------------------------------------------------
# Part 3: Dicts and sets
# ---------------------------------------------------------------------------

def word_count(text):
    """13. Count words (case-insensitive, split on whitespace).

    word_count("the cat The hat") -> {"the": 2, "cat": 1, "hat": 1}
    Hint: d[w] = d.get(w, 0) + 1   — or look up collections.Counter.
    """
    raise NotImplementedError


def group_by_length(words):
    """14. Group words by their length.

    group_by_length(["hi", "yo", "cat"]) -> {2: ["hi", "yo"], 3: ["cat"]}
    Hint: d.setdefault(key, []).append(...)  — or collections.defaultdict(list).
    """
    raise NotImplementedError


def common_items(a, b):
    """15. Return the items that appear in both lists, sorted, no duplicates.

    common_items([3, 1, 2, 2], [2, 3, 4]) -> [2, 3]
    Hint: set intersection (&), then sorted().
    """
    raise NotImplementedError


def dedupe_keep_order(items):
    """16. Remove duplicates but keep the first-seen order.

    dedupe_keep_order([3, 1, 3, 2, 1]) -> [3, 1, 2]
    Hint: set() loses order. Dict keys are unique AND ordered... dict.fromkeys()
    """
    raise NotImplementedError


def invert_dict(d):
    """17. Swap keys and values.

    invert_dict({"a": 1, "b": 2}) -> {1: "a", 2: "b"}
    Hint: a dict comprehension over d.items().
    """
    raise NotImplementedError


# ---------------------------------------------------------------------------
# Part 4: Functions
# ---------------------------------------------------------------------------

def add_item(item, items=[]):
    """18. FIX THE BUG. This should add `item` to `items` and return it,
    using a fresh list when none is passed in.

    add_item("x") -> ["x"]
    add_item("y") -> ["y"]      but right now it returns ["x", "y"]. Why?
    Hint: default values are created ONCE, when the function is defined.
    """
    items.append(item)
    return items


def make_counter():
    """19. Return a function that returns 1, then 2, then 3... each call.
    Each counter is independent.

    c = make_counter(); c() -> 1; c() -> 2
    Hint: an inner def + the `nonlocal` keyword (a closure, like in JS).
    """
    raise NotImplementedError


def apply_all(value, *funcs):
    """20. Pass `value` through each function in order and return the result.

    apply_all(3, lambda x: x + 1, lambda x: x * 10) -> 40
    apply_all(5) -> 5
    Hint: *funcs collects extra positional args into a tuple.
    """
    raise NotImplementedError


def build_url(base, **params):
    """21. Build a URL with query parameters, in the order they were given.

    build_url("https://x.com/search", q="cats", page=2) -> "https://x.com/search?q=cats&page=2"
    build_url("https://x.com")                         -> "https://x.com"
    Hint: **params collects keyword args into a dict. "&".join(...) an f-string comprehension.
    """
    raise NotImplementedError


# ---------------------------------------------------------------------------
# Part 5: Classes
# ---------------------------------------------------------------------------

class Point:
    """22. Replace this whole class with a @dataclass Point with fields x and y,
    plus a method distance_to(other) returning the straight-line distance.

    Point(0, 0).distance_to(Point(3, 4)) -> 5.0
    Point(1, 2) == Point(1, 2)           -> True   (dataclass gives you __eq__)
    It must also be usable in a set / as a dict key.
    Hint: @dataclass(frozen=True), and math.dist() or math.hypot().
    """

    def __init__(self, x, y):
        raise NotImplementedError


class Stack:
    """23. A simple stack (last in, first out) backed by a list.

    s = Stack(); s.push(1); s.push(2)
    s.peek() -> 2;  s.pop() -> 2;  len(s) -> 1
    pop() or peek() on an empty stack should raise IndexError.
    `if s:` should be False when empty — implementing __len__ gives you that for free.
    """

    def __init__(self):
        raise NotImplementedError

    def push(self, item):
        raise NotImplementedError

    def pop(self):
        raise NotImplementedError

    def peek(self):
        raise NotImplementedError

    def __len__(self):
        raise NotImplementedError


# ---------------------------------------------------------------------------
# Part 6: Errors, files and match
# ---------------------------------------------------------------------------

def safe_int(text, default=0):
    """24. Convert text to int, or return `default` if it can't be converted.

    safe_int("42") -> 42;  safe_int("abc") -> 0;  safe_int(None) -> 0
    Hint: try/except. Which exceptions do int("abc") and int(None) raise? Try them in the REPL.
    """
    raise NotImplementedError


def count_lines(path):
    """25. Return the number of lines in the text file at `path`.

    Hint: `with open(path) as f:` — a file object can be looped over line by line.
    """
    raise NotImplementedError


def longest_line(path):
    """26. Return the longest line in the file (without its trailing newline).
    Return "" for an empty file.

    Hint: max(..., key=len, default="") and str.rstrip("\\n").
    """
    raise NotImplementedError


def describe(value):
    """27. Use a `match` statement to describe a value:

    None           -> "nothing"
    an int         -> "number 5"         (for 5)
    a str          -> "text 'hi'"         (for "hi")  hint: f"text {value!r}"
    []             -> "empty list"
    [7]            -> "one item: 7"
    [1, 2, 3]      -> "list starting with 1"
    anything else  -> "something else"

    Hint: case None:, case int():, case str():, case []:, case [x]:, case [first, *_]:, case _:
    """
    raise NotImplementedError
