{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "71de4dc3",
   "metadata": {},
   "source": [
    "# Desafíos de regex: la bandeja y el log de PyShop\n",
    "\n",
    "Diez desafíos graduados, de extraer un pedido a anonimizar la bandeja completa. Cada uno trae:\n",
    "\n",
    "1. un **enunciado**;\n",
    "2. una **función vacía** que debes completar;\n",
    "3. una celda de **pruebas** con `assert`. Mientras la función no esté resuelta, imprime «pendiente» y el\n",
    "   notebook sigue.\n",
    "\n",
    "Las **soluciones** están al final, en una sección separada, junto con la cifra que cada una produce sobre la\n",
    "bandeja o el log. Resuelve primero y compara después. Los desafíos 1, 2, 3, 4 y 10 son las piezas del proyecto\n",
    "final."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "20dbf43b",
   "metadata": {},
   "source": [
    "## Datos y función de pruebas"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "9269caa5",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-07T17:27:31.616742Z",
     "iopub.status.busy": "2026-10-07T17:27:31.616624Z",
     "iopub.status.idle": "2026-10-07T17:27:31.649968Z",
     "shell.execute_reply": "2026-10-07T17:27:31.649009Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Python 3.13.14\n",
      "600 tickets | 2000 líneas de log | 97,737 caracteres\n",
      "Ticket T-0001\n",
      "De: Valeria Ortiz <valeria.ortiz@ejemplo.org>\n",
      "Hola, la factura del pedido PS-42098 tiene un error. Pagué $4696 con efectivo el 24 de febrero de 2026. Por favor favor respondan pronto.\n"
     ]
    }
   ],
   "source": [
    "import re\n",
    "import sys\n",
    "import time\n",
    "from collections import Counter\n",
    "\n",
    "print(\"Python\", sys.version.split()[0])\n",
    "\n",
    "# Generadores del curso (iguales en todos los notebooks): bandeja de soporte y log de PyShop\n",
    "import random\n",
    "\n",
    "NOMBRES = [\"Ana López\", \"Luis Pérez\", \"María Gómez\", \"Carlos Ruiz\", \"Sofía Díaz\", \"Jorge Torres\",\n",
    "           \"Lucía Romero\", \"Pedro Castro\", \"Elena Vargas\", \"Diego Morales\", \"Valeria Ortiz\", \"Andrés Silva\"]\n",
    "DOMINIOS = [\"correo.com\", \"mail.net\", \"ejemplo.org\", \"pyshop.mx\"]\n",
    "MESES = [\"enero\", \"febrero\", \"marzo\", \"abril\", \"mayo\", \"junio\", \"julio\", \"agosto\", \"septiembre\",\n",
    "         \"octubre\", \"noviembre\", \"diciembre\"]\n",
    "TEMAS = {\n",
    "    \"envio\": [\"mi pedido {p} no ha llegado\", \"el envío del pedido {p} viene con retraso\",\n",
    "              \"la guía del pedido {p} no se actualiza\"],\n",
    "    \"devolucion\": [\"quiero devolver el pedido {p}\", \"solicito el reembolso del pedido {p}\",\n",
    "                   \"necesito cambiar el producto del pedido {p}\"],\n",
    "    \"pago\": [\"me cobraron dos veces el pedido {p}\", \"el pago del pedido {p} fue rechazado\",\n",
    "             \"no veo reflejado el pago del pedido {p}\"],\n",
    "    \"danado\": [\"el pedido {p} llegó dañado\", \"el producto del pedido {p} llegó roto\",\n",
    "               \"al pedido {p} le faltan piezas\"],\n",
    "    \"factura\": [\"necesito la factura del pedido {p}\", \"la factura del pedido {p} tiene un error\",\n",
    "                \"no me llegó la factura del pedido {p}\"],\n",
    "}\n",
    "PAGOS = [\"tarjeta\", \"transferencia\", \"efectivo\", \"PayPal\"]\n",
    "\n",
    "\n",
    "def _usuario(nombre):\n",
    "    n, a = nombre.lower().split()\n",
    "    tabla = str.maketrans(\"áéíóú\", \"aeiou\")\n",
    "    return f\"{n}.{a}\".translate(tabla)\n",
    "\n",
    "\n",
    "def generar_tickets(n=600, semilla=42):\n",
    "    \"\"\"Lista de n tickets de soporte (str) con formatos mezclados a propósito.\"\"\"\n",
    "    rng = random.Random(semilla)\n",
    "    tickets = []\n",
    "    for i in range(1, n + 1):\n",
    "        nombre = rng.choice(NOMBRES)\n",
    "        correo = f\"{_usuario(nombre)}{rng.choice(['', str(rng.randint(1, 99))])}@{rng.choice(DOMINIOS)}\"\n",
    "        num = rng.randint(10000, 99999)\n",
    "        pedido = rng.choices([f\"PS-{num}\", f\"ps-{num}\", f\"PS {num}\"], weights=[80, 12, 8])[0]\n",
    "        dia, mes = rng.randint(1, 28), rng.randint(1, 10)\n",
    "        fecha = rng.choice([f\"2026-{mes:02d}-{dia:02d}\", f\"{dia:02d}/{mes:02d}/2026\",\n",
    "                            f\"{dia} de {MESES[mes - 1]} de 2026\"])\n",
    "        tel = \"\".join(str(rng.randint(0, 9)) for _ in range(8))\n",
    "        lada = rng.choice([\"55\", \"33\", \"81\"])\n",
    "        telefono = rng.choice([f\"{lada} {tel[:4]} {tel[4:]}\", f\"({lada}) {tel[:4]}-{tel[4:]}\",\n",
    "                               f\"+52 {lada} {tel[:4]} {tel[4:]}\", f\"{lada}{tel}\"])\n",
    "        pesos, centavos = rng.randint(99, 4999), rng.choice([0, 0, 50, 90, 99])\n",
    "        monto = rng.choice([f\"${pesos:,}.{centavos:02d}\", f\"{pesos}.{centavos:02d} MXN\", f\"${pesos}\"])\n",
    "        tema = rng.choice(list(TEMAS))\n",
    "        frase = rng.choice(TEMAS[tema]).format(p=pedido)\n",
    "        partes = [f\"Hola, {frase}.\"]\n",
    "        if rng.random() < 0.8:\n",
    "            partes.append(f\"Pagué {monto} con {rng.choice(PAGOS)} el {fecha}.\")\n",
    "        if rng.random() < 0.6:\n",
    "            partes.append(f\"Mi teléfono es {telefono}.\")\n",
    "        if rng.random() < 0.05:  # errata con palabra repetida (para retrorreferencias)\n",
    "            partes.append(\"Por favor favor respondan pronto.\")\n",
    "        texto = f\"Ticket T-{i:04d}\\nDe: {nombre} <{correo}>\\n\" + \" \".join(partes)\n",
    "        tickets.append(texto)\n",
    "    return tickets\n",
    "\n",
    "\n",
    "RUTAS = [\"/\", \"/productos\", \"/productos/{id}\", \"/carrito\", \"/api/pedidos/{id}\", \"/api/pagos\",\n",
    "         \"/login\", \"/buscar?q=audifonos\"]\n",
    "\n",
    "\n",
    "def generar_log(n=2000, semilla=7):\n",
    "    \"\"\"Lista de n líneas de log de acceso (formato tipo Common Log + tiempo de respuesta).\"\"\"\n",
    "    rng = random.Random(semilla)\n",
    "    ips = [f\"10.0.{rng.randint(0, 3)}.{rng.randint(2, 254)}\" for _ in range(40)]\n",
    "    lineas = []\n",
    "    seg = 8 * 3600\n",
    "    for _ in range(n):\n",
    "        seg += rng.randint(1, 20)\n",
    "        h, m, s = seg // 3600 % 24, seg // 60 % 60, seg % 60\n",
    "        ruta = rng.choice(RUTAS).format(id=rng.randint(1, 500))\n",
    "        metodo = \"POST\" if ruta in (\"/api/pagos\", \"/login\", \"/carrito\") and rng.random() < 0.7 else \"GET\"\n",
    "        estado = rng.choices([200, 201, 301, 404, 500], weights=[78, 6, 4, 9, 3])[0]\n",
    "        if metodo == \"GET\" and estado == 201:\n",
    "            estado = 200\n",
    "        bytes_ = 0 if estado in (301, 404) else rng.randint(200, 25000)\n",
    "        tiempo = round(rng.uniform(0.005, 0.3) if estado != 500 else rng.uniform(0.5, 2.5), 3)\n",
    "        lineas.append(f'{rng.choice(ips)} - - [07/Oct/2026:{h:02d}:{m:02d}:{s:02d} -0600] '\n",
    "                      f'\"{metodo} {ruta} HTTP/1.1\" {estado} {bytes_} {tiempo}')\n",
    "    return lineas\n",
    "\n",
    "tickets = generar_tickets()\n",
    "log = generar_log()\n",
    "bandeja = \"\\n\\n\".join(tickets)\n",
    "print(len(tickets), \"tickets |\", len(log), \"líneas de log |\", f\"{len(bandeja):,} caracteres\")\n",
    "print(tickets[0])\n",
    "\n",
    "def probar(nombre, pruebas, estricto=False):\n",
    "    \"\"\"Corre las pruebas de un ejercicio. Si aún no está resuelto, imprime 'pendiente' sin detener el notebook.\"\"\"\n",
    "    try:\n",
    "        pruebas()\n",
    "    except (AssertionError, NotImplementedError, TypeError, AttributeError) as e:\n",
    "        if estricto:\n",
    "            raise\n",
    "        print(f\"{nombre}: pendiente ({type(e).__name__})\")\n",
    "    else:\n",
    "        print(f\"{nombre}: correcto\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "194a94ce",
   "metadata": {},
   "source": [
    "## Desafío 1. Pedidos\n",
    "\n",
    "Escribe `pedidos(texto)` que devuelva la lista de pedidos normalizados a `PS-ddddd`, aceptando\n",
    "`PS-12345`, `ps-12345` y `PS 12345`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "674612f0",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-07T17:27:31.651613Z",
     "iopub.status.busy": "2026-10-07T17:27:31.651456Z",
     "iopub.status.idle": "2026-10-07T17:27:31.655842Z",
     "shell.execute_reply": "2026-10-07T17:27:31.655031Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Desafío 1: pendiente (NotImplementedError)\n"
     ]
    }
   ],
   "source": [
    "def pedidos(texto):\n",
    "    raise NotImplementedError  # tu código\n",
    "\n",
    "\n",
    "def pruebas_1(f):\n",
    "    assert f(\"Pedidos ps-12345, PS 67890 y PS-11111\") == [\"PS-12345\", \"PS-67890\", \"PS-11111\"]\n",
    "    assert f(\"Sin pedido, solo PS-482\") == []\n",
    "\n",
    "probar(\"Desafío 1\", lambda: pruebas_1(pedidos))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "882bc338",
   "metadata": {},
   "source": [
    "## Desafío 2. Fechas a ISO\n",
    "\n",
    "Escribe `a_iso(fecha)` que convierta `2026-06-25`, `28/02/2026` y «24 de febrero de 2026» a\n",
    "`aaaa-mm-dd`, y devuelva `None` si el texto no es una fecha en esos formatos. Usa `MESES`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "0e08fc20",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-07T17:27:31.658084Z",
     "iopub.status.busy": "2026-10-07T17:27:31.657930Z",
     "iopub.status.idle": "2026-10-07T17:27:31.662560Z",
     "shell.execute_reply": "2026-10-07T17:27:31.661976Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Desafío 2: pendiente (NotImplementedError)\n"
     ]
    }
   ],
   "source": [
    "def a_iso(fecha):\n",
    "    raise NotImplementedError  # tu código\n",
    "\n",
    "\n",
    "def pruebas_2(f):\n",
    "    assert f(\"24 de febrero de 2026\") == \"2026-02-24\"\n",
    "    assert f(\"28/02/2026\") == \"2026-02-28\"\n",
    "    assert f(\"2026-06-25\") == \"2026-06-25\"\n",
    "    assert f(\"3 de marzo de 2026\") == \"2026-03-03\"\n",
    "    assert f(\"ayer\") is None\n",
    "\n",
    "probar(\"Desafío 2\", lambda: pruebas_2(a_iso))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3139183f",
   "metadata": {},
   "source": [
    "## Desafío 3. Teléfonos\n",
    "\n",
    "Escribe `tel10(texto)` que devuelva el primer teléfono del texto con solo 10 dígitos, o `None`. Formatos:\n",
    "`8116155940`, `(55) 3010-3105`, `55 1234 5678` y `+52 55 1234 5678`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "a3f092f4",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-07T17:27:31.664182Z",
     "iopub.status.busy": "2026-10-07T17:27:31.664054Z",
     "iopub.status.idle": "2026-10-07T17:27:31.668135Z",
     "shell.execute_reply": "2026-10-07T17:27:31.667384Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Desafío 3: pendiente (NotImplementedError)\n"
     ]
    }
   ],
   "source": [
    "def tel10(texto):\n",
    "    raise NotImplementedError  # tu código\n",
    "\n",
    "\n",
    "def pruebas_3(f):\n",
    "    assert f(\"+52 55 1234 5678\") == \"5512345678\"\n",
    "    assert f(\"Mi teléfono es (33) 3010-3105.\") == \"3330103105\"\n",
    "    assert f(\"81 1615 5940\") == \"8116155940\"\n",
    "    assert f(\"Sin teléfono\") is None\n",
    "\n",
    "probar(\"Desafío 3\", lambda: pruebas_3(tel10))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7d041e47",
   "metadata": {},
   "source": [
    "## Desafío 4. Montos\n",
    "\n",
    "Escribe `a_float(monto)` que convierta `$1,269.50`, `4491.00 MXN` y `$4696` en `float`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "77791c6a",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-07T17:27:31.669766Z",
     "iopub.status.busy": "2026-10-07T17:27:31.669636Z",
     "iopub.status.idle": "2026-10-07T17:27:31.673169Z",
     "shell.execute_reply": "2026-10-07T17:27:31.672667Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Desafío 4: pendiente (NotImplementedError)\n"
     ]
    }
   ],
   "source": [
    "def a_float(monto):\n",
    "    raise NotImplementedError  # tu código\n",
    "\n",
    "\n",
    "def pruebas_4(f):\n",
    "    assert f(\"$1,269.50\") == 1269.5\n",
    "    assert f(\"4491.00 MXN\") == 4491.0\n",
    "    assert f(\"$4696\") == 4696.0\n",
    "\n",
    "probar(\"Desafío 4\", lambda: pruebas_4(a_float))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "03cfb323",
   "metadata": {},
   "source": [
    "## Desafío 5. Palabras repetidas\n",
    "\n",
    "Escribe `sin_repetidas(texto)` que elimine las palabras escritas dos veces seguidas («favor favor» →\n",
    "«favor») sin tocar casos como «el elefante»."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "f0f17a78",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-07T17:27:31.674576Z",
     "iopub.status.busy": "2026-10-07T17:27:31.674465Z",
     "iopub.status.idle": "2026-10-07T17:27:31.677860Z",
     "shell.execute_reply": "2026-10-07T17:27:31.677169Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Desafío 5: pendiente (NotImplementedError)\n"
     ]
    }
   ],
   "source": [
    "def sin_repetidas(texto):\n",
    "    raise NotImplementedError  # tu código\n",
    "\n",
    "\n",
    "def pruebas_5(f):\n",
    "    assert f(\"Por favor favor respondan pronto.\") == \"Por favor respondan pronto.\"\n",
    "    assert f(\"el elefante\") == \"el elefante\"\n",
    "    assert f(\"el el pedido\") == \"el pedido\"\n",
    "\n",
    "probar(\"Desafío 5\", lambda: pruebas_5(sin_repetidas))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "411f50ef",
   "metadata": {},
   "source": [
    "## Desafío 6. Rutas del log\n",
    "\n",
    "Escribe `normaliza_ruta(ruta)` que cambie cada segmento numérico por `{id}`: `/api/pedidos/243` →\n",
    "`/api/pedidos/{id}`. `/buscar?q=audifonos` no cambia. Luego cuenta los 404 por ruta normalizada."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "d1d81296",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-07T17:27:31.679035Z",
     "iopub.status.busy": "2026-10-07T17:27:31.678923Z",
     "iopub.status.idle": "2026-10-07T17:27:31.681939Z",
     "shell.execute_reply": "2026-10-07T17:27:31.681547Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Desafío 6: pendiente (NotImplementedError)\n"
     ]
    }
   ],
   "source": [
    "def normaliza_ruta(ruta):\n",
    "    raise NotImplementedError  # tu código\n",
    "\n",
    "\n",
    "def pruebas_6(f):\n",
    "    assert f(\"/api/pedidos/243\") == \"/api/pedidos/{id}\"\n",
    "    assert f(\"/productos/17\") == \"/productos/{id}\"\n",
    "    assert f(\"/buscar?q=audifonos\") == \"/buscar?q=audifonos\"\n",
    "\n",
    "probar(\"Desafío 6\", lambda: pruebas_6(normaliza_ruta))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "77c26426",
   "metadata": {},
   "source": [
    "## Desafío 7. Contraseñas\n",
    "\n",
    "Escribe `segura(pw)` que devuelva `True` si la contraseña tiene al menos una mayúscula, una minúscula,\n",
    "un dígito, un símbolo y 10 caracteres."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "91155f53",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-07T17:27:31.683182Z",
     "iopub.status.busy": "2026-10-07T17:27:31.683077Z",
     "iopub.status.idle": "2026-10-07T17:27:31.686149Z",
     "shell.execute_reply": "2026-10-07T17:27:31.685671Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Desafío 7: pendiente (NotImplementedError)\n"
     ]
    }
   ],
   "source": [
    "def segura(pw):\n",
    "    raise NotImplementedError  # tu código\n",
    "\n",
    "\n",
    "def pruebas_7(f):\n",
    "    casos = {\"pyshop2026\": False, \"PyShop2026\": False, \"PyShop2026!\": True, \"Py!2026a\": False}\n",
    "    assert {pw: f(pw) for pw in casos} == casos\n",
    "\n",
    "probar(\"Desafío 7\", lambda: pruebas_7(segura))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "96784caf",
   "metadata": {},
   "source": [
    "## Desafío 8. CSV simple\n",
    "\n",
    "Escribe `campos(linea)` que separe por coma o punto y coma y quite los espacios de ambos lados de cada\n",
    "campo."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "0eb3edeb",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-07T17:27:31.687290Z",
     "iopub.status.busy": "2026-10-07T17:27:31.687186Z",
     "iopub.status.idle": "2026-10-07T17:27:31.689937Z",
     "shell.execute_reply": "2026-10-07T17:27:31.689581Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Desafío 8: pendiente (NotImplementedError)\n"
     ]
    }
   ],
   "source": [
    "def campos(linea):\n",
    "    raise NotImplementedError  # tu código\n",
    "\n",
    "\n",
    "def pruebas_8(f):\n",
    "    assert f(\"tarjeta, efectivo;transferencia ,PayPal\") == [\"tarjeta\", \"efectivo\", \"transferencia\", \"PayPal\"]\n",
    "    assert f(\" PS-42098 ;  4696 ,efectivo \") == [\"PS-42098\", \"4696\", \"efectivo\"]\n",
    "\n",
    "probar(\"Desafío 8\", lambda: pruebas_8(campos))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d793399b",
   "metadata": {},
   "source": [
    "## Desafío 9. Etiquetas\n",
    "\n",
    "Escribe `sin_etiquetas(html)` que quite todas las etiquetas HTML y deje solo el texto."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "37c34c2e",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-07T17:27:31.690835Z",
     "iopub.status.busy": "2026-10-07T17:27:31.690712Z",
     "iopub.status.idle": "2026-10-07T17:27:31.693261Z",
     "shell.execute_reply": "2026-10-07T17:27:31.692917Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Desafío 9: pendiente (NotImplementedError)\n"
     ]
    }
   ],
   "source": [
    "def sin_etiquetas(html):\n",
    "    raise NotImplementedError  # tu código\n",
    "\n",
    "\n",
    "def pruebas_9(f):\n",
    "    assert f(\"<b>Pedido</b> y <b>Factura</b>\") == \"Pedido y Factura\"\n",
    "    assert f('<p class=\"nota\">Pago <em>rechazado</em></p>') == \"Pago rechazado\"\n",
    "\n",
    "probar(\"Desafío 9\", lambda: pruebas_9(sin_etiquetas))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8d18bf5b",
   "metadata": {},
   "source": [
    "## Desafío 10. Anonimizar\n",
    "\n",
    "Escribe `anonimiza(ticket)` que cambie cada correo por `***@dominio` y cada teléfono por `** **** ****`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "4c64d599",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-07T17:27:31.694187Z",
     "iopub.status.busy": "2026-10-07T17:27:31.694098Z",
     "iopub.status.idle": "2026-10-07T17:27:31.696704Z",
     "shell.execute_reply": "2026-10-07T17:27:31.696325Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Desafío 10: pendiente (NotImplementedError)\n"
     ]
    }
   ],
   "source": [
    "def anonimiza(ticket):\n",
    "    raise NotImplementedError  # tu código\n",
    "\n",
    "\n",
    "def pruebas_10(f):\n",
    "    t = f(tickets[1])\n",
    "    assert \"<***@ejemplo.org>\" in t and \"Mi teléfono es ** **** ****.\" in t\n",
    "    assert \"maria.gomez90\" not in t\n",
    "\n",
    "probar(\"Desafío 10\", lambda: pruebas_10(anonimiza))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3ea62576",
   "metadata": {},
   "source": [
    "---\n",
    "# Soluciones\n",
    "\n",
    "Cada solución vuelve a definir la función del desafío, corre sus pruebas en modo estricto (si una fallara, el\n",
    "notebook se detendría) y la aplica a los datos completos."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7cee59f9",
   "metadata": {},
   "source": [
    "### Solución 1. Pedidos"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "0437065c",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-07T17:27:31.697797Z",
     "iopub.status.busy": "2026-10-07T17:27:31.697709Z",
     "iopub.status.idle": "2026-10-07T17:27:31.702809Z",
     "shell.execute_reply": "2026-10-07T17:27:31.702372Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Solución 1: correcto\n",
      "600 pedidos, 597 distintos\n"
     ]
    }
   ],
   "source": [
    "def pedidos(texto):\n",
    "    return [f\"PS-{n}\" for n in re.findall(r\"(?i)\\bps[- ]?(\\d{5})\\b\", texto)]\n",
    "\n",
    "\n",
    "probar(\"Solución 1\", lambda: pruebas_1(pedidos), estricto=True)\n",
    "todos = [p for t in tickets for p in pedidos(t)]\n",
    "print(len(todos), \"pedidos,\", len(set(todos)), \"distintos\")\n",
    "assert (len(todos), len(set(todos))) == (600, 597)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f16c6691",
   "metadata": {},
   "source": [
    "### Solución 2. Fechas a ISO"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "aaca103a",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-07T17:27:31.704046Z",
     "iopub.status.busy": "2026-10-07T17:27:31.703948Z",
     "iopub.status.idle": "2026-10-07T17:27:31.711577Z",
     "shell.execute_reply": "2026-10-07T17:27:31.711079Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Solución 2: correcto\n",
      "488 fechas, 0 sin convertir\n"
     ]
    }
   ],
   "source": [
    "def a_iso(fecha):\n",
    "    if re.fullmatch(r\"\\d{4}-\\d{2}-\\d{2}\", fecha):\n",
    "        return fecha\n",
    "    if m := re.fullmatch(r\"(\\d{2})/(\\d{2})/(\\d{4})\", fecha):\n",
    "        return f\"{m[3]}-{m[2]}-{m[1]}\"\n",
    "    if m := re.fullmatch(r\"(\\d{1,2}) de (\\w+) de (\\d{4})\", fecha):\n",
    "        if m[2].lower() in MESES:\n",
    "            return f\"{m[3]}-{MESES.index(m[2].lower()) + 1:02d}-{int(m[1]):02d}\"\n",
    "    return None\n",
    "\n",
    "\n",
    "probar(\"Solución 2\", lambda: pruebas_2(a_iso), estricto=True)\n",
    "FECHA = re.compile(r\"\\d{4}-\\d{2}-\\d{2}|\\d{2}/\\d{2}/\\d{4}|\\d{1,2} de [a-z]+ de \\d{4}\")\n",
    "fechas = [m.group() for t in tickets for m in FECHA.finditer(t)]\n",
    "isos = [a_iso(f) for f in fechas]\n",
    "print(len(isos), \"fechas,\", isos.count(None), \"sin convertir\")\n",
    "assert len(isos) == 488 and isos.count(None) == 0"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7780f43c",
   "metadata": {},
   "source": [
    "### Solución 3. Teléfonos"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "9f1761ad",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-07T17:27:31.712877Z",
     "iopub.status.busy": "2026-10-07T17:27:31.712763Z",
     "iopub.status.idle": "2026-10-07T17:27:31.722023Z",
     "shell.execute_reply": "2026-10-07T17:27:31.721068Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Solución 3: correcto\n",
      "369 teléfonos\n"
     ]
    }
   ],
   "source": [
    "TEL = re.compile(r\"(?:\\+52 )?\\(?(\\d{2})\\)?[ -]?(\\d{4})[ -]?(\\d{4})\")\n",
    "\n",
    "def tel10(texto):\n",
    "    m = TEL.search(texto)\n",
    "    return \"\".join(m.groups()) if m else None\n",
    "\n",
    "\n",
    "probar(\"Solución 3\", lambda: pruebas_3(tel10), estricto=True)\n",
    "con_tel = [tel10(t) for t in tickets if tel10(t)]\n",
    "print(len(con_tel), \"teléfonos\")\n",
    "assert len(con_tel) == 369"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "71e49200",
   "metadata": {},
   "source": [
    "### Solución 4. Montos"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "8d3a9309",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-07T17:27:31.723038Z",
     "iopub.status.busy": "2026-10-07T17:27:31.722938Z",
     "iopub.status.idle": "2026-10-07T17:27:31.726967Z",
     "shell.execute_reply": "2026-10-07T17:27:31.726594Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Solución 4: correcto\n",
      "488 montos, suma 1,211,689.39\n"
     ]
    }
   ],
   "source": [
    "def a_float(monto):\n",
    "    return float(re.sub(r\"[$,]|\\s*MXN\", \"\", monto))\n",
    "\n",
    "\n",
    "probar(\"Solución 4\", lambda: pruebas_4(a_float), estricto=True)\n",
    "MONTO = re.compile(r\"Pagué (\\$?[\\d,]+(?:\\.\\d{2})?(?: MXN)?)\")\n",
    "valores = [a_float(m.group(1)) for t in tickets if (m := MONTO.search(t))]\n",
    "print(len(valores), \"montos, suma\", f\"{sum(valores):,.2f}\")\n",
    "assert len(valores) == 488 and round(sum(valores), 2) == 1211689.39"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "dd436341",
   "metadata": {},
   "source": [
    "### Solución 5. Palabras repetidas"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "id": "d38ee624",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-07T17:27:31.727917Z",
     "iopub.status.busy": "2026-10-07T17:27:31.727788Z",
     "iopub.status.idle": "2026-10-07T17:27:31.733822Z",
     "shell.execute_reply": "2026-10-07T17:27:31.733461Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Solución 5: correcto\n",
      "21 tickets corregidos\n"
     ]
    }
   ],
   "source": [
    "def sin_repetidas(texto):\n",
    "    return re.sub(r\"\\b(\\w+) \\1\\b\", r\"\\1\", texto)\n",
    "\n",
    "\n",
    "probar(\"Solución 5\", lambda: pruebas_5(sin_repetidas), estricto=True)\n",
    "corregidos = sum(sin_repetidas(t) != t for t in tickets)\n",
    "print(corregidos, \"tickets corregidos\")\n",
    "assert corregidos == 21"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "99873935",
   "metadata": {},
   "source": [
    "### Solución 6. Rutas del log"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "7f43af14",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-07T17:27:31.734760Z",
     "iopub.status.busy": "2026-10-07T17:27:31.734669Z",
     "iopub.status.idle": "2026-10-07T17:27:31.738612Z",
     "shell.execute_reply": "2026-10-07T17:27:31.738240Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Solución 6: correcto\n",
      "[('/productos', 29), ('/', 27), ('/buscar?q=audifonos', 27), ('/api/pedidos/{id}', 26), ('/api/pagos', 25)]\n"
     ]
    }
   ],
   "source": [
    "def normaliza_ruta(ruta):\n",
    "    return re.sub(r\"/\\d+(?=/|$)\", \"/{id}\", ruta)\n",
    "\n",
    "\n",
    "probar(\"Solución 6\", lambda: pruebas_6(normaliza_ruta), estricto=True)\n",
    "LINEA = re.compile(r'\"(?P<metodo>[A-Z]+) (?P<ruta>\\S+) HTTP/[\\d.]+\" (?P<estado>\\d{3})')\n",
    "regs = [LINEA.search(l) for l in log]\n",
    "r404 = Counter(normaliza_ruta(m[\"ruta\"]) for m in regs if m[\"estado\"] == \"404\")\n",
    "print(r404.most_common(5))\n",
    "assert r404.most_common(1) == [(\"/productos\", 29)]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0b742caf",
   "metadata": {},
   "source": [
    "### Solución 7. Contraseñas"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "id": "b1128291",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-07T17:27:31.739541Z",
     "iopub.status.busy": "2026-10-07T17:27:31.739418Z",
     "iopub.status.idle": "2026-10-07T17:27:31.742258Z",
     "shell.execute_reply": "2026-10-07T17:27:31.741907Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Solución 7: correcto\n",
      "{'pyshop2026': False, 'PyShop2026': False, 'PyShop2026!': True, 'Py!2026a': False}\n"
     ]
    }
   ],
   "source": [
    "def segura(pw):\n",
    "    patron = r\"(?=.*[A-Z])(?=.*[a-z])(?=.*\\d)(?=.*[^\\w\\s]).{10,}\"\n",
    "    return re.fullmatch(patron, pw) is not None\n",
    "\n",
    "\n",
    "probar(\"Solución 7\", lambda: pruebas_7(segura), estricto=True)\n",
    "print({pw: segura(pw) for pw in [\"pyshop2026\", \"PyShop2026\", \"PyShop2026!\", \"Py!2026a\"]})"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b0db8a73",
   "metadata": {},
   "source": [
    "### Solución 8. CSV simple"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "id": "924d88bd",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-07T17:27:31.743287Z",
     "iopub.status.busy": "2026-10-07T17:27:31.743165Z",
     "iopub.status.idle": "2026-10-07T17:27:31.745954Z",
     "shell.execute_reply": "2026-10-07T17:27:31.745561Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Solución 8: correcto\n",
      "['tarjeta', 'efectivo', 'transferencia', 'PayPal']\n"
     ]
    }
   ],
   "source": [
    "def campos(linea):\n",
    "    return re.split(r\"\\s*[;,]\\s*\", linea.strip())\n",
    "\n",
    "\n",
    "probar(\"Solución 8\", lambda: pruebas_8(campos), estricto=True)\n",
    "print(campos(\"tarjeta, efectivo;transferencia ,PayPal\"))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c5a9d55a",
   "metadata": {},
   "source": [
    "### Solución 9. Etiquetas"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "id": "23f99f6f",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-07T17:27:31.746958Z",
     "iopub.status.busy": "2026-10-07T17:27:31.746835Z",
     "iopub.status.idle": "2026-10-07T17:27:31.749868Z",
     "shell.execute_reply": "2026-10-07T17:27:31.749506Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Solución 9: correcto\n",
      "Pedido y Factura\n"
     ]
    }
   ],
   "source": [
    "def sin_etiquetas(html):\n",
    "    return re.sub(r\"<[^>]+>\", \"\", html)\n",
    "\n",
    "\n",
    "probar(\"Solución 9\", lambda: pruebas_9(sin_etiquetas), estricto=True)\n",
    "print(sin_etiquetas(\"<b>Pedido</b> y <b>Factura</b>\"))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "54e11f37",
   "metadata": {},
   "source": [
    "### Solución 10. Anonimizar"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "id": "81e07a74",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-10-07T17:27:31.750727Z",
     "iopub.status.busy": "2026-10-07T17:27:31.750607Z",
     "iopub.status.idle": "2026-10-07T17:27:31.770456Z",
     "shell.execute_reply": "2026-10-07T17:27:31.770045Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Solución 10: correcto\n",
      "Ticket T-0002\n",
      "De: María Gómez <***@ejemplo.org>\n",
      "Hola, la guía del pedido PS-46421 no se actualiza. Pagué 4491.00 MXN con efectivo el 2026-06-25. Mi teléfono es ** **** ****.\n",
      "quedan 0 correos y 0 teléfonos\n"
     ]
    }
   ],
   "source": [
    "CORREO = re.compile(r\"[\\w.+-]+@([\\w-]+(?:\\.[\\w-]+)+)\")\n",
    "\n",
    "def anonimiza(ticket):\n",
    "    return TEL.sub(\"** **** ****\", CORREO.sub(r\"***@\\1\", ticket))\n",
    "\n",
    "\n",
    "probar(\"Solución 10\", lambda: pruebas_10(anonimiza), estricto=True)\n",
    "anon = [anonimiza(t) for t in tickets]\n",
    "quedan_correos = sum(bool(re.search(r\"[\\w.+-]+(?<!\\*)@\", a)) for a in anon)\n",
    "quedan_tels = sum(bool(TEL.search(a)) for a in anon)\n",
    "print(anon[1])\n",
    "print(\"quedan\", quedan_correos, \"correos y\", quedan_tels, \"teléfonos\")\n",
    "assert quedan_correos == 0 and quedan_tels == 0"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "80a9d791",
   "metadata": {},
   "source": [
    "## Resumen\n",
    "\n",
    "| # | Desafío | Cifra |\n",
    "|---|---|---|\n",
    "| 1 | Pedidos | 600 pedidos, 597 distintos |\n",
    "| 2 | Fechas | 488 a ISO, 0 sin convertir |\n",
    "| 3 | Teléfonos | 369 |\n",
    "| 4 | Montos | 488, suma 1,211,689.39 |\n",
    "| 5 | Repetidas | 21 tickets corregidos |\n",
    "| 6 | Rutas | 404 más frecuente: `/productos` con 29 |\n",
    "| 7 | Contraseñas | solo `PyShop2026!` |\n",
    "| 8 | CSV | 4 campos limpios |\n",
    "| 9 | Etiquetas | «Pedido y Factura» |\n",
    "| 10 | Anonimizar | 0 correos y 0 teléfonos |"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.13.14"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
