# Chapter Tests: Coding Challenges

After each 5-day chapter, do **two** things:

1. Take the quiz: `python quiz.py <chapter number>` (pass mark 4/5).
2. Solve the coding challenge below **without looking at the lessons or the solution**. Then compare.

Rule: if you fail either, re-do that chapter's practice tasks before moving on.

| Chapter | Days | Challenge |
|---|---|---|
| 1 | 1-5 | Clean a messy name and print a sentence |
| 2 | 6-10 | Grade and shipping calculator |
| 3 | 11-15 | Stats on a list of scores |
| 4 | 16-20 | Word counter with a function |
| 5 | 21-25 | Safe number input and JSON save |
| 6 | 26-30 | Overdue invoice finder |
| 7 | 31-35 | BankAccount class |
| 8 | 36-40 | Function plus pytest tests |
| 9 | 41-45 | API to Excel |
| 10 | 46-50 | Sales summary with pandas |
| 11 | 51-55 | SQLite customer store |
| 12 | 56-60 | Concurrent fetch and clean structure |

---
## Chapter 1: Clean a messy name
Given `raw = "  aLI   rAZa "`, produce `Ali Raza` and print `Hello, Ali Raza! Your name has 8 letters.`

<details><summary>Solution</summary>

```python
raw = "  aLI   rAZa "
name = " ".join(raw.split()).title()
letters = len(name.replace(" ", ""))
print(f"Hello, {name}! Your name has {letters} letters.")
```
</details>

## Chapter 2: Grade and shipping
Ask for a score (0-100) and print the grade (A 90+, B 75+, C 60+, else Fail). Then ask for an order amount: free shipping over 5000, 150 over 2000, else 300.

<details><summary>Solution</summary>

```python
score = int(input("Score: "))
if score >= 90: grade = "A"
elif score >= 75: grade = "B"
elif score >= 60: grade = "C"
else: grade = "Fail"
print("Grade:", grade)

amount = float(input("Order amount: "))
if amount > 5000: ship = 0
elif amount > 2000: ship = 150
else: ship = 300
print("Shipping:", ship)
```
</details>

## Chapter 3: Stats on a list
For `scores = [72, 88, 95, 60, 79, 91, 55, 84]` print the average, highest, lowest, the top 3 (highest first), and how many are above average.

<details><summary>Solution</summary>

```python
scores = [72, 88, 95, 60, 79, 91, 55, 84]
avg = sum(scores) / len(scores)
print(round(avg, 2), max(scores), min(scores))
print(sorted(scores, reverse=True)[:3])
print(sum(1 for s in scores if s > avg))
```
</details>

## Chapter 4: Word counter function
Write `count_words(text)` that returns a dictionary of word counts (ignore case and punctuation `.,!?`). Print the 3 most common words.

<details><summary>Solution</summary>

```python
def count_words(text):
    counts = {}
    for word in text.lower().split():
        word = word.strip(".,!?")
        if word:
            counts[word] = counts.get(word, 0) + 1
    return counts

result = count_words("The cat and the hat. The end!")
top3 = sorted(result.items(), key=lambda kv: kv[1], reverse=True)[:3]
print(top3)   # [('the', 3), ('cat', 1), ('and', 1)]
```
</details>

## Chapter 5: Safe input and JSON save
Write `get_number(prompt)` that keeps asking until the user enters a valid number. Ask for 3 numbers, then save `{"numbers": [...], "total": ...}` to `result.json`.

<details><summary>Solution</summary>

```python
import json

def get_number(prompt):
    while True:
        try:
            return float(input(prompt))
        except ValueError:
            print("Please type a number.")

nums = [get_number(f"Number {i}: ") for i in range(1, 4)]
with open("result.json", "w", encoding="utf-8") as f:
    json.dump({"numbers": nums, "total": sum(nums)}, f, indent=2)
```
</details>

## Chapter 6: Overdue invoice finder
Given a list of dicts with `id` and `date` (text `YYYY-MM-DD`), print the ids older than 30 days from today and how many days overdue each is.

<details><summary>Solution</summary>

```python
from datetime import datetime, date

invoices = [
    {"id": 1, "date": "2026-01-05"},
    {"id": 2, "date": date.today().isoformat()},
]
today = date.today()
for inv in invoices:
    age = (today - datetime.strptime(inv["date"], "%Y-%m-%d").date()).days
    if age > 30:
        print(f"Invoice {inv['id']} is overdue by {age - 30} days")
```
</details>

## Chapter 7: BankAccount class
`BankAccount(owner, balance=0)` with `deposit(amount)`, `withdraw(amount)` (raise `ValueError` if not enough money or amount <= 0), and `__str__` showing the balance.

<details><summary>Solution</summary>

```python
class BankAccount:
    def __init__(self, owner, balance=0):
        self.owner, self.balance = owner, balance

    def deposit(self, amount):
        if amount <= 0:
            raise ValueError("Amount must be positive")
        self.balance += amount

    def withdraw(self, amount):
        if amount <= 0 or amount > self.balance:
            raise ValueError("Invalid withdrawal")
        self.balance -= amount

    def __str__(self):
        return f"{self.owner}: Rs {self.balance:,.2f}"

acc = BankAccount("Sam", 1000)
acc.deposit(500); acc.withdraw(200)
print(acc)   # Sam: Rs 1,300.00
```
</details>

## Chapter 8: Function plus pytest
Write `is_palindrome(text)` (ignore case and spaces) in `words.py` and 4 tests in `test_words.py`.

<details><summary>Solution</summary>

```python
# words.py
def is_palindrome(text):
    cleaned = "".join(text.lower().split())
    return cleaned == cleaned[::-1]

# test_words.py
from words import is_palindrome

def test_simple():        assert is_palindrome("level")
def test_with_spaces():   assert is_palindrome("Nurses Run")
def test_not():           assert not is_palindrome("python")
def test_empty():         assert is_palindrome("")
```
</details>

## Chapter 9: API to Excel
Fetch the current temperature for 3 cities from Open-Meteo (use latitude/longitude) and save city and temperature to `weather.xlsx`.

<details><summary>Solution</summary>

```python
import requests
from openpyxl import Workbook

cities = {"Lahore": (31.55, 74.34), "Karachi": (24.86, 67.01), "Islamabad": (33.68, 73.05)}
wb = Workbook(); ws = wb.active
ws.append(["City", "Temp C"])
for city, (lat, lon) in cities.items():
    r = requests.get("https://api.open-meteo.com/v1/forecast",
                     params={"latitude": lat, "longitude": lon, "current_weather": True},
                     timeout=10)
    r.raise_for_status()
    ws.append([city, r.json()["current_weather"]["temperature"]])
wb.save("weather.xlsx")
```
</details>

## Chapter 10: Sales summary with pandas
Given `sales.csv` with `customer,amount,date`, print the top 3 customers by total and the total per month.

<details><summary>Solution</summary>

```python
import pandas as pd

df = pd.read_csv("sales.csv", parse_dates=["date"]).dropna()
print(df.groupby("customer")["amount"].sum().nlargest(3))
print(df.groupby(df["date"].dt.to_period("M"))["amount"].sum())
```
</details>

## Chapter 11: SQLite customer store
Create `shop.db` with a `customers(id, name, city)` table, insert 3 customers, and print only those in a city chosen by the user (use `?` placeholders).

<details><summary>Solution</summary>

```python
import sqlite3

con = sqlite3.connect("shop.db")
con.execute("CREATE TABLE IF NOT EXISTS customers(id INTEGER PRIMARY KEY, name TEXT, city TEXT)")
con.executemany("INSERT INTO customers(name, city) VALUES (?, ?)",
                [("Ali", "Lahore"), ("Sara", "Karachi"), ("Omar", "Lahore")])
con.commit()
city = input("City: ")
for row in con.execute("SELECT name FROM customers WHERE city = ?", (city,)):
    print(row[0])
con.close()
```
</details>

## Chapter 12: Concurrent fetch
Fetch 5 URLs at the same time with `asyncio` + `httpx` (`pip install httpx`) and print each status code and the total time. Put the code in a `main()` with the `__main__` guard.

<details><summary>Solution</summary>

```python
import asyncio, time
import httpx

URLS = ["https://example.com", "https://httpbin.org/get", "https://www.python.org",
        "https://pypi.org", "https://docs.python.org/3/"]

async def fetch(client, url):
    r = await client.get(url, timeout=15)
    return url, r.status_code

async def main():
    start = time.time()
    async with httpx.AsyncClient() as client:
        for url, status in await asyncio.gather(*(fetch(client, u) for u in URLS)):
            print(status, url)
    print(f"Total {time.time() - start:.2f}s")

if __name__ == "__main__":
    asyncio.run(main())
```
</details>
