diff --git a/tareas/examen/Parcial2_solo codigo.py b/tareas/examen/Parcial2_solo codigo.py new file mode 100644 index 0000000..647e608 --- /dev/null +++ b/tareas/examen/Parcial2_solo codigo.py @@ -0,0 +1,152 @@ +NOMBRE = "Brandom Rodriguez" # TU NOMBRE AQUI +CARNET = "202506893" # TU CARNET AQUI +if NOMBRE == "Nombre Apellido" or CARNET == "202300000": + raise ValueError("Completa tu nombre y carnet antes de continuar.") +print(f"Estudiante : {NOMBRE}") +print(f"Carnet : {CARNET}") +#-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +#Ejercicio 1 + +#Parte a +import requests +URL_BASE = "https://api.nasa.gov/DONKI/GST" +API_KEY = "DEMO_KEY" +# Agrega también los parámetros startDate y endDate: +startDate = "2024-05-01" +endDate = "2024-05-31" +# Construcción de la URL +url = ( + f"{URL_BASE}" + f"?startDate={startDate}" + f"&endDate={endDate}" + f"&api_key={API_KEY}" +) +# Completa la llamada — usa timeout=15 +respuesta = requests.get(url, timeout=15) +# Verifica que la respuesta fue exitosa antes de parsear el JSON +if not respuesta.ok: + print(f"Error {respuesta.status_code}: {respuesta.text}") + raise SystemExit("No se pudo obtener la respuesta. Intenta de nuevo.") +tormentas = respuesta.json() +print(f"Solicitud exitosa ✓ — {len(tormentas)} tormentas recibidas") + +#Parte b +print(f"Total de tormentas en el período: {len(tormentas)}") +# Recorrer cada tormenta +for tormenta in tormentas: + gst_id = tormenta.get("gstID", "N/A") + start_time = tormenta.get("startTime", "N/A") + print(f"ID: {gst_id} | Inicio: {start_time}") +#-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +#Ejercicio 2 + +#Parte a +for tormenta in tormentas: + kp_max = 0 +# recorrer la lista allKpIndex + for medicion in tormenta.get("allKpIndex", []): + kp = medicion.get("kpIndex", 0) + if kp > kp_max: + kp_max = kp + print(f"{tormenta['startTime']} | Kp máx = {kp_max:.2f}") + +#Parte b +tormenta_mas_intensa = None +kp_global_max = 0 +for tormenta in tormentas: + kp_max = 0 +# calcular kp máximo de esta tormenta + for medicion in tormenta.get("allKpIndex", []): + kp = medicion.get("kpIndex", 0) + if kp > kp_max: + kp_max = kp +# comparar con el máximo global + if kp_max > kp_global_max: + kp_global_max = kp_max + tormenta_mas_intensa = tormenta +if tormenta_mas_intensa: + print("\nTormenta más intensa:") + print(f"Inicio: {tormenta_mas_intensa['startTime']}") + print(f"Kp máximo global: {kp_global_max:.2f}") +#-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +#Ejercicio 3 + +#Parte a +def clasificar_kp(kp): + """Clasifica la intensidad de una tormenta según el índice Kp""" + kp = int(kp) # redondea hacia abajo + if kp < 4: + return "Quieto" + elif kp == 4: + return "Activo" + elif kp == 5: + return "G1 - Menor" + elif kp == 6: + return "G2 - Moderada" + elif kp == 7: + return "G3 - Fuerte" + elif kp == 8: + return "G4 - Severa" + else: # kp >= 9 + return "G5 - Fuerte" +#Prueba tu función con estos valores — verifica que los resultados son correctos: +for kp_prueba in [2.0, 4.0, 5.33, 6.67, 7.0, 8.67, 9.0]: + print(f"kp={kp_prueba:.2f} → {clasificar_kp(kp_prueba)}") + +#Parte b +print(f"\n{'Fecha inicio':<22} {'Kp máx':>7} {'Categoría'}") +print("-" * 50) +for tormenta in tormentas: + kp_max = 0 +# calcular el Kp máximo de la tormenta + for medicion in tormenta.get("allKpIndex", []): + kp = medicion.get("kpIndex", 0) + if kp > kp_max: + kp_max = kp + categoria = clasificar_kp(kp_max) + print(f"{tormenta['startTime']:<22} {kp_max:>7.2f} {categoria}") +#-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +#Ejercicio 4 + +def analizar_tormenta(tormenta): + """ + Analiza un evento de tormenta geomagnética. + Parámetro: + tormenta (dict): un elemento de la lista retornada por el endpoint GST. + Retorna: + dict con las claves: id, inicio, kp_max, kp_min, kp_promedio, + num_mediciones, categoria, eventos_vinculados. + """ + mediciones = tormenta["allKpIndex"] +# Extraer valores kpIndex + kp_valores = [m["kpIndex"] for m in mediciones] + resultado = { + "id": tormenta["gstID"], + "inicio": tormenta["startTime"], + "kp_max": max(kp_valores), + "kp_min": min(kp_valores), + "kp_promedio": round(sum(kp_valores) / len(kp_valores), 2), + "num_mediciones": len(mediciones), + "categoria": clasificar_kp(max(kp_valores)), + "eventos_vinculados": len(tormenta["linkedEvents"] or []), + } + return resultado +for tormenta in tormentas: + r = analizar_tormenta(tormenta) + print(f"ID: {r['id']}") + print(f"Inicio: {r['inicio']}") + print(f"Kp Máx: {r['kp_max']}") + print(f"Kp Mín: {r['kp_min']}") + print(f"Kp Promedio: {r['kp_promedio']}") + print(f"Número de mediciones: {r['num_mediciones']}") + print(f"Categoría: {r['categoria']}") + print(f"Eventos vinculados: {r['eventos_vinculados']}") + print("-" * 40) +#-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +print("Conculsiones:") + +print("1. La tormenta mas intensa fue Inicio:2024-05-10T15:00Z con un Kp maximo de 9.00 y su clasificacion G5-Fuerte. Su kp es el valor maximo posible lo que implica que fue una tormenta geomagnetica extrema") +print("2. Frecuencia :Se registraron 5 tormentas en un periodo de 15 dias, esto significa una alta activida geomagnetica. Tambien que hay una concentracion clara entre 10 y el 17 de mayor.Intensidad: 4 de las 5 tormantas fueron G2 con kp de 6.00 a 6.67, solo hubo una tormenta intesa de clasificacion G5. Esto implica una actividad moderada. Eventos vinculados: La tormenta mas intensa tiene un mayor numero de mediciones que en total son 13 y de cantidad de eventos vinculados 6 en total. La tormentas moderadas tienen solamente entr 1 o 2 eventos.") +print("3. Una tormenta nivel G5-Fuerte podria haber causado interrupciones en los sistemas de navegacion (GPS),apagones, Auroras visibles en latitudes inusualmente bajas y fallos en equipos ") + +#-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- diff --git a/tareas/examen/examen_parcial2_estudiante.ipynb b/tareas/examen/examen_parcial2_estudiante.ipynb new file mode 100644 index 0000000..ffde3a3 --- /dev/null +++ b/tareas/examen/examen_parcial2_estudiante.ipynb @@ -0,0 +1,835 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "id": "title", + "metadata": {}, + "source": [ + "# Examen Parcial 2 — Programación 1 (F12)\n", + "## Tormentas Geomagnéticas con la API de NASA / DONKI\n", + "\n", + "**Nombre:** Brandom Aroldo Rodriguez Gonzalez \n", + "**Carnet:** 202506893 \n", + "**Fecha:** 24/04/2026 \n", + "**Punteo total:** 100 puntos\n", + "\n", + "---\n", + "\n", + "| Ejercicio | Tema | Puntos |\n", + "|---|---|:---:|\n", + "| 1a | Construir la URL y realizar la solicitud HTTP | 10 |\n", + "| 1b | Explorar la lista de tormentas con un ciclo `for` | 10 |\n", + "| 2 | Calcular el Kp máximo e identificar la tormenta más intensa | 20 |\n", + "| 3 | Función `clasificar_kp()` con condicionales | 25 |\n", + "| 4 | Función `analizar_tormenta()` que retorna un diccionario | 35 |\n", + "| | **Total** | **100** |\n", + "\n", + "---\n", + "\n", + "> **Instrucciones generales**\n", + "> - Completa cada ejercicio en la celda indicada.\n", + "> - Ejecuta las celdas **en orden** de arriba hacia abajo.\n", + "> - Puedes consultar tus apuntes y el notebook de clase `XML_JSON_APIs.ipynb`.\n", + "> - Entrega el notebook con **todas las celdas ejecutadas** (con output visible)." + ] + }, + { + "cell_type": "markdown", + "id": "background", + "metadata": {}, + "source": [ + "---\n", + "## Contexto: ¿Qué es una tormenta geomagnética?\n", + "\n", + "El Sol emite constantemente partículas cargadas (viento solar). Cuando ocurre una erupción solar intensa, una ola de partículas choca con el campo magnético de la Tierra y provoca una **tormenta geomagnética**.\n", + "\n", + "Estos eventos pueden:\n", + "- Generar auroras boreales visibles en latitudes bajas\n", + "- Interferir con satélites GPS y comunicaciones de radio\n", + "- En casos extremos, dañar redes eléctricas (como el apagón de Quebec en 1989)\n", + "\n", + "### Índice Kp — escala de intensidad\n", + "\n", + "El **índice Kp** (0–9) mide la perturbación del campo magnético terrestre:\n", + "\n", + "| Kp | Categoría | Descripción |\n", + "|---|---|---|\n", + "| 0 – 3 | Quieto | Sin tormenta |\n", + "| 4 | Activo | Perturbación menor |\n", + "| 5 | **G1** — Menor | Auroras en latitudes altas |\n", + "| 6 | **G2** — Moderada | Auroras hasta latitud 55° |\n", + "| 7 | **G3** — Fuerte | Auroras hasta latitud 50° |\n", + "| 8 | **G4** — Severa | Problemas en redes eléctricas |\n", + "| 9 | **G5** — Extrema | Apagones posibles, auroras tropicales |\n", + "\n", + "La tormenta de mayo 2024 alcanzó **G5** — la más intensa en 20 años." + ] + }, + { + "cell_type": "markdown", + "id": "api-docs", + "metadata": {}, + "source": [ + "---\n", + "## El endpoint: DONKI / GST\n", + "\n", + "**DONKI** = Space Weather Database Of Notifications, Knowledge, Information \n", + "**GST** = Geomagnetic Storm\n", + "\n", + "```\n", + "GET https://api.nasa.gov/DONKI/GST\n", + "```\n", + "\n", + "| Parámetro | Tipo | Default | Descripción |\n", + "|---|---|---|---|\n", + "| `startDate` | YYYY-MM-DD | 30 días atrás | Inicio del rango de fechas |\n", + "| `endDate` | YYYY-MM-DD | hoy | Fin del rango de fechas |\n", + "| `api_key` | string | DEMO_KEY | Tu API key de api.nasa.gov |\n", + "\n", + "**Ejemplo de URL:**\n", + "```\n", + "https://api.nasa.gov/DONKI/GST?startDate=2024-05-01&endDate=2024-05-31&api_key=DEMO_KEY\n", + "```\n", + "\n", + "### Estructura de la respuesta\n", + "\n", + "La API devuelve una **lista** de eventos. Cada evento es un diccionario con esta estructura:\n", + "\n", + "```json\n", + "{\n", + " \"gstID\": \"2024-05-10T17:00:00-GST-001\",\n", + " \"startTime\": \"2024-05-10T17:00Z\",\n", + " \"allKpIndex\": [\n", + " { \"observedTime\": \"2024-05-10T21:00Z\", \"kpIndex\": 8.67, \"source\": \"NOAA\" },\n", + " { \"observedTime\": \"2024-05-11T00:00Z\", \"kpIndex\": 9.0, \"source\": \"NOAA\" }\n", + " ],\n", + " \"linkedEvents\": [\n", + " { \"activityID\": \"2024-05-08T21:08:00-CME-001\" }\n", + " ],\n", + " \"link\": \"https://webtools.ccmc.gsfc.nasa.gov/DONKI/view/GST/...\"\n", + "}\n", + "```\n", + "\n", + "**Campos importantes:**\n", + "- `gstID` — identificador único del evento\n", + "- `startTime` — cuándo comenzó la tormenta (formato ISO 8601 UTC)\n", + "- `allKpIndex` — lista de mediciones Kp durante la tormenta\n", + "- `linkedEvents` — eventos espaciales relacionados (erupciones, CME) — puede ser `None`" + ] + }, + { + "cell_type": "markdown", + "id": "setup-title", + "metadata": {}, + "source": [ + "---\n", + "## Paso 1 — Configuración de la API Key\n", + "\n", + "### Obtener tu API key (gratis)\n", + "\n", + "1. Ve a **https://api.nasa.gov**\n", + "2. Completa el formulario con tu nombre y correo electrónico\n", + "3. Haz clic en **\"Signup\"**\n", + "4. Revisa tu correo — recibirás la key en minutos\n", + "5. La key tiene este formato: `TU_API_KEY_AQUI_XXXXXXXXXXXXXXXXXXXXXXXX`\n", + "\n", + "Con tu propia key puedes hacer **1,000 solicitudes por hora** (vs 30 con DEMO_KEY).\n", + "\n", + "---\n", + "\n", + "### Configurar la variable de entorno `NASA_API_KEY`\n", + "\n", + "Una variable de entorno guarda tu key **fuera del código**, para que no quede expuesta \n", + "en el archivo del notebook ni en el historial de git.\n", + "\n", + "#### Linux / macOS — temporal (solo la sesión actual)\n", + "```bash\n", + "export NASA_API_KEY=\"tu_key_aqui\"\n", + "jupyter notebook\n", + "```\n", + "\n", + "#### Linux / macOS — permanente\n", + "Agrega esta línea al final de `~/.bashrc` (bash) o `~/.zshrc` (zsh):\n", + "```bash\n", + "echo 'export NASA_API_KEY=\"tu_key_aqui\"' >> ~/.bashrc\n", + "source ~/.bashrc # aplicar sin reiniciar\n", + "```\n", + "\n", + "#### Windows — PowerShell (temporal)\n", + "```powershell\n", + "$env:NASA_API_KEY = \"tu_key_aqui\"\n", + "jupyter notebook\n", + "```\n", + "\n", + "#### Windows — permanente (Panel de control)\n", + "1. Busca **\"Variables de entorno\"** en el menú Inicio\n", + "2. Clic en **\"Editar las variables de entorno del sistema\"**\n", + "3. Botón **\"Variables de entorno...\"**\n", + "4. En \"Variables de usuario\" → **Nueva**\n", + "5. Nombre: `NASA_API_KEY` | Valor: tu key\n", + "6. Aceptar y **reiniciar** Jupyter\n", + "\n", + "#### Verificar que está configurada\n", + "```bash\n", + "# Linux/macOS\n", + "echo $NASA_API_KEY\n", + "\n", + "# Windows PowerShell\n", + "echo $env:NASA_API_KEY\n", + "```" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "setup-code", + "metadata": {}, + "outputs": [], + "source": [ + "import os\n", + "import requests\n", + "import json\n", + "import time\n", + "\n", + "# Cargar la API key desde la variable de entorno.\n", + "# Si no está configurada, usa DEMO_KEY como respaldo (30 req/hora).\n", + "API_KEY = os.getenv(\"NASA_API_KEY\", \"\").strip() or \"DEMO_KEY\"\n", + "\n", + "if API_KEY == \"DEMO_KEY\":\n", + " print(\"⚠ Usando DEMO_KEY — límite: 30 solicitudes/hora\")\n", + " print(\" Configura NASA_API_KEY para mayor límite (ver instrucciones arriba).\")\n", + "else:\n", + " print(f\"✓ API key cargada: {API_KEY[:4]}{'*' * (len(API_KEY) - 4)}\")\n", + "\n", + "print(\"\\nLibrerías importadas correctamente ✓\")" + ] + }, + { + "cell_type": "markdown", + "id": "ident-md", + "metadata": {}, + "source": [ + "---\n", + "## Identificacion del estudiante\n", + "\n", + "Completa tu nombre y carnet en la siguiente celda y **ejecutala antes de comenzar**. \n", + "Estos datos quedan registrados en el output del notebook junto con la posicion de la ISS \n", + "en el momento exacto en que realizas el examen." + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "id": "ident-code", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Estudiante : Brandom Rodriguez\n", + "Carnet : 202506893\n" + ] + } + ], + "source": [ + "# Completa tus datos\n", + "NOMBRE = \"Brandom Rodriguez\" # TU NOMBRE AQUI\n", + "CARNET = \"202506893\" # TU CARNET AQUI\n", + "\n", + "if NOMBRE == \"Nombre Apellido\" or CARNET == \"202300000\":\n", + " raise ValueError(\"Completa tu nombre y carnet antes de continuar.\")\n", + "\n", + "print(f\"Estudiante : {NOMBRE}\")\n", + "print(f\"Carnet : {CARNET}\")" + ] + }, + { + "cell_type": "markdown", + "id": "ej1-md", + "metadata": {}, + "source": [ + "---\n", + "## Ejercicio 1 — Obtener y explorar los datos (20 pts)\n", + "\n", + "### Parte a) — Solicitud al endpoint (10 pts)\n", + "\n", + "Se te da la URL base del endpoint. Construye la URL completa usando un f-string e incluye los parámetros `startDate`, `endDate` y `api_key`. Luego realiza la solicitud y verifica que fue exitosa.\n", + "\n", + "---\n", + "\n", + "### ¿Por qué verificar el código de estado antes de leer el JSON?\n", + "\n", + "Cuando hacemos una solicitud HTTP el servidor siempre responde con un **código de estado numérico** que indica si todo salió bien o hubo un problema.\n", + "\n", + "El código **200** significa *\"OK — la solicitud fue exitosa y el cuerpo de la respuesta contiene los datos pedidos\"*.\n", + "\n", + "Si el servidor devuelve un código diferente (por ejemplo **503 - Service Unavailable** o **429 - Too Many Requests**), el cuerpo de la respuesta **no contiene JSON válido** — puede estar vacío o contener un mensaje de error en texto plano. Si intentamos llamar `.json()` directamente sin verificar, el programa lanzará un `JSONDecodeError`.\n", + "\n", + "Por eso siempre debemos verificar que `respuesta.status_code == 200` (o equivalentemente `respuesta.ok`) **antes** de intentar parsear la respuesta.\n", + "\n", + "> **Escribe en la celda de código siguiente: ¿qué imprimirías tú para que el usuario sepa qué salió mal cuando el código no es 200?**" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "id": "ej1-code", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Solicitud exitosa ✓ — 5 tormentas recibidas\n" + ] + } + ], + "source": [ + "import requests\n", + "URL_BASE = \"https://api.nasa.gov/DONKI/GST\"\n", + "API_KEY = \"DEMO_KEY\"\n", + "# Agrega también los parámetros startDate y endDate:\n", + "# startDate = \"2024-05-01\"\n", + "# endDate = \"2024-05-31\"\n", + "# Hint: los parámetros van separados por \"&\" → ?param1=val1¶m2=val2\n", + "startDate = \"2024-05-01\"\n", + "endDate = \"2024-05-31\"\n", + "url = f\"{URL_BASE}?startDate={startDate}&endDate={endDate}&api_key={API_KEY}\" # TU CÓDIGO AQUÍ\n", + "\n", + "# Completa la llamada — usa timeout=15\n", + "respuesta = requests.get(url, timeout=15) # TU CÓDIGO AQUÍ\n", + "\n", + "# Verifica que la respuesta fue exitosa antes de parsear el JSON\n", + "# Hint: usa respuesta.ok o compara respuesta.status_code con 200\n", + "# Hint: si hay error, imprime el código y el cuerpo — respuesta.text tiene el mensaje\n", + "if not respuesta.ok: # TU CÓDIGO AQUÍ — condición de error\n", + " print(f\"Error {respuesta.status_code}: {respuesta.text}\") # TU CÓDIGO AQUÍ — mensaje informativo\n", + " raise SystemExit(\"No se pudo obtener la respuesta. Intenta de nuevo.\")\n", + "\n", + "tormentas = respuesta.json()\n", + "print(f\"Solicitud exitosa ✓ — {len(tormentas)} tormentas recibidas\")" + ] + }, + { + "cell_type": "markdown", + "id": "ej1-url-warning", + "metadata": {}, + "source": [ + "> ⚠️ **Cuidado con exponer tu API key** \n", + "> Puedes descomentar el `print` de la celda siguiente para verificar que la URL se formó correctamente, pero **vuelve a comentarlo antes de guardar y entregar el notebook**. Si lo dejas activo, tu API key quedará visible en el output del archivo." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "ej1-url-check", + "metadata": {}, + "outputs": [], + "source": [ + "# Descomenta la siguiente línea para verificar que la URL se formó correctamente.\n", + "# ⚠ Vuelve a comentarla antes de entregar — el output guarda tu API key en el archivo.\n", + "\n", + "# print(\"URL:\", url)" + ] + }, + { + "cell_type": "markdown", + "id": "ej1b-md", + "metadata": {}, + "source": [ + "### Parte b) — Explorar la lista de tormentas (10 pts)\n", + "\n", + "Usando un ciclo `for`, imprime cuántas tormentas hubo en el período y el `gstID` y `startTime` de cada una." + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "id": "ej1b-code", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Total de tormentas en el período: 5\n", + "ID: 2024-05-02T15:00:00-GST-001 | Inicio: 2024-05-02T15:00Z\n", + "ID: 2024-05-10T15:00:00-GST-001 | Inicio: 2024-05-10T15:00Z\n", + "ID: 2024-05-12T21:00:00-GST-001 | Inicio: 2024-05-12T21:00Z\n", + "ID: 2024-05-16T06:00:00-GST-001 | Inicio: 2024-05-16T06:00Z\n", + "ID: 2024-05-17T18:00:00-GST-001 | Inicio: 2024-05-17T18:00Z\n" + ] + } + ], + "source": [ + "# Hint: len(tormentas) da el total de eventos\n", + "# Hint: cada elemento de tormentas es un dict — accede con tormenta[\"gstID\"], etc.\n", + "\n", + "# TU CÓDIGO AQUÍ\n", + "print(f\"Total de tormentas en el período: {len(tormentas)}\")\n", + "\n", + "# Recorrer cada tormenta\n", + "for tormenta in tormentas:\n", + " gst_id = tormenta.get(\"gstID\", \"N/A\")\n", + " start_time = tormenta.get(\"startTime\", \"N/A\")\n", + " \n", + " print(f\"ID: {gst_id} | Inicio: {start_time}\")" + ] + }, + { + "cell_type": "markdown", + "id": "ej2-md", + "metadata": {}, + "source": [ + "---\n", + "## Ejercicio 2 — Kp máximo por tormenta (20 pts)\n", + "\n", + "Cada tormenta contiene una lista `allKpIndex` con múltiples mediciones a lo largo del tiempo.\n", + "\n", + "**a) (10 pts)** Para cada tormenta, encuentra el **valor máximo de Kp** usando un ciclo `for` sobre `allKpIndex`. Imprime el `startTime` y el Kp máximo de cada tormenta.\n", + "\n", + "**b) (10 pts)** Encuentra e imprime la tormenta **más intensa** del período (la que tuvo el mayor Kp máximo entre todas las tormentas)." + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "id": "ej2-code", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + " 2024-05-02T15:00Z Kp máx = 6.67\n", + " 2024-05-10T15:00Z Kp máx = 9.00\n", + " 2024-05-12T21:00Z Kp máx = 6.33\n", + " 2024-05-16T06:00Z Kp máx = 6.00\n", + " 2024-05-17T18:00Z Kp máx = 6.00\n", + "\n", + "Tormenta más intensa:\n", + "Inicio: 2024-05-10T15:00Z\n", + "Kp máximo global: 9.00\n" + ] + } + ], + "source": [ + "# ── Parte a) ──────────────────────────────────────────────────────────────────\n", + "# Hint: allKpIndex es una lista de dicts, cada uno con la clave \"kpIndex\"\n", + "# Hint: para encontrar el máximo de una lista puedes usar la función max()\n", + "# o un ciclo que compare con una variable auxiliar (kp_max = 0)\n", + "\n", + "for tormenta in tormentas:\n", + " # TU CÓDIGO AQUÍ — obtener el kp máximo de esta tormenta\n", + " kp_max = 0\n", + " for medicion in tormenta.get(\"allKpIndex\", []):\n", + " kp = medicion.get(\"kpIndex\", 0)\n", + " if kp > kp_max:\n", + " kp_max = kp\n", + "\n", + " print(f\" {tormenta['startTime']} Kp máx = {kp_max:.2f}\")\n", + "\n", + "# ── Parte b) ──────────────────────────────────────────────────────────────────\n", + "# Hint: necesitas dos variables auxiliares:\n", + "# tormenta_mas_intensa = None\n", + "# kp_global_max = 0\n", + "# Recorre todas las tormentas y actualiza estas variables cuando encuentres un Kp mayor\n", + "\n", + "# TU CÓDIGO AQUÍ\n", + "tormenta_mas_intensa = None\n", + "kp_global_max = 0\n", + "for tormenta in tormentas:\n", + " kp_max = 0\n", + " for medicion in tormenta.get(\"allKpIndex\", []):\n", + " kp = medicion.get(\"kpIndex\", 0)\n", + " if kp > kp_max:\n", + " kp_max = kp\n", + " if kp_max > kp_global_max:\n", + " kp_global_max = kp_max\n", + " tormenta_mas_intensa = tormenta\n", + "if tormenta_mas_intensa:\n", + " print(\"\\nTormenta más intensa:\")\n", + " print(f\"Inicio: {tormenta_mas_intensa['startTime']}\")\n", + " print(f\"Kp máximo global: {kp_global_max:.2f}\")" + ] + }, + { + "cell_type": "markdown", + "id": "ej3-md", + "metadata": {}, + "source": [ + "---\n", + "## Ejercicio 3 — Clasificar la severidad con condicionales (25 pts)\n", + "\n", + "**a) (15 pts)** Escribe una función `clasificar_kp(kp)` que reciba un valor de Kp (float) y retorne una cadena con la categoría según la tabla del contexto:\n", + "- Kp < 4 → `\"Quieto\"`\n", + "- Kp == 4 → `\"Activo\"`\n", + "- Kp == 5 → `\"G1 - Menor\"`\n", + "- Kp == 6 → `\"G2 - Moderada\"`\n", + "- Kp == 7 → `\"G3 - Fuerte\"`\n", + "- Kp == 8 → `\"G4 - Severa\"`\n", + "- Kp >= 9 → `\"G5 - Extrema\"`\n", + "\n", + "> **Nota:** el índice Kp puede ser decimal (ej. 8.67). Usa `int(kp)` para redondear hacia abajo y comparar.\n", + "\n", + "**b) (10 pts)** Usa tu función para imprimir una tabla con cada tormenta, su Kp máximo y su categoría." + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "id": "ej3-code", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + " kp=2.00 → Quieto\n", + " kp=4.00 → Activo\n", + " kp=5.33 → G1 - Menor\n", + " kp=6.67 → G2 - Moderada\n", + " kp=7.00 → G3 - Fuerte\n", + " kp=8.67 → G4 - Severa\n", + " kp=9.00 → G5 - Fuerte\n", + "\n", + "Fecha inicio Kp máx Categoría\n", + "--------------------------------------------------\n", + "2024-05-02T15:00Z 6.67 G2 - Moderada\n", + "2024-05-10T15:00Z 9.00 G5 - Fuerte\n", + "2024-05-12T21:00Z 6.33 G2 - Moderada\n", + "2024-05-16T06:00Z 6.00 G2 - Moderada\n", + "2024-05-17T18:00Z 6.00 G2 - Moderada\n" + ] + } + ], + "source": [ + "# ── Parte a) ──────────────────────────────────────────────────────────────────\n", + "# Hint: usa if / elif / else\n", + "# Hint: int(8.67) == 8 — esto te permite usar comparaciones exactas con enteros\n", + "\n", + "def clasificar_kp(kp):\n", + " \"\"\"Clasifica la intensidad de una tormenta según el índice Kp.\"\"\"\n", + " # TU CÓDIGO AQUÍ\n", + " kp = int(kp) # redondea hacia abajo\n", + " \n", + " if kp < 4:\n", + " return \"Quieto\"\n", + " elif kp == 4:\n", + " return \"Activo\"\n", + " elif kp == 5:\n", + " return \"G1 - Menor\"\n", + " elif kp == 6:\n", + " return \"G2 - Moderada\"\n", + " elif kp == 7:\n", + " return \"G3 - Fuerte\"\n", + " elif kp == 8:\n", + " return \"G4 - Severa\"\n", + " else: # kp >= 9\n", + " return \"G5 - Fuerte\"\n", + "\n", + "\n", + "# Prueba tu función con estos valores — verifica que los resultados son correctos:\n", + "for kp_prueba in [2.0, 4.0, 5.33, 6.67, 7.0, 8.67, 9.0]:\n", + " print(f\" kp={kp_prueba:.2f} → {clasificar_kp(kp_prueba)}\")\n", + "\n", + "# ── Parte b) ──────────────────────────────────────────────────────────────────\n", + "print(f\"\\n{'Fecha inicio':<22} {'Kp máx':>7} {'Categoría'}\")\n", + "print(\"-\" * 50)\n", + "\n", + "# TU CÓDIGO AQUÍ — recorre tormentas, calcula kp_max, llama clasificar_kp()\n", + "for tormenta in tormentas:\n", + " kp_max = 0\n", + " for medicion in tormenta.get(\"allKpIndex\", []):\n", + " kp = medicion.get(\"kpIndex\", 0)\n", + " if kp > kp_max:\n", + " kp_max = kp\n", + " categoria = clasificar_kp(kp_max)\n", + " print(f\"{tormenta['startTime']:<22} {kp_max:>7.2f} {categoria}\")" + ] + }, + { + "cell_type": "markdown", + "id": "ej4-md", + "metadata": {}, + "source": [ + "---\n", + "## Ejercicio 4 — Función de análisis completa (35 pts)\n", + "\n", + "Escribe una función `analizar_tormenta(tormenta)` que reciba **un evento** de la lista `tormentas` y retorne un **diccionario** con las siguientes claves:\n", + "\n", + "| Clave | Valor esperado |\n", + "|---|---|\n", + "| `\"id\"` | el `gstID` del evento |\n", + "| `\"inicio\"` | el `startTime` |\n", + "| `\"kp_max\"` | el valor Kp más alto entre todas las mediciones |\n", + "| `\"kp_min\"` | el valor Kp más bajo entre todas las mediciones |\n", + "| `\"kp_promedio\"` | promedio de todos los valores Kp (redondeado a 2 decimales) |\n", + "| `\"num_mediciones\"` | cuántas mediciones hay en `allKpIndex` |\n", + "| `\"categoria\"` | resultado de llamar `clasificar_kp(kp_max)` |\n", + "| `\"eventos_vinculados\"` | número de eventos en `linkedEvents` (0 si es `None`) |\n", + "\n", + "Luego aplícala a **todas las tormentas** con un ciclo `for` e imprime un resumen de cada una." + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "id": "ej4-code", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "ID: 2024-05-02T15:00:00-GST-001\n", + "Inicio: 2024-05-02T15:00Z\n", + "Kp Máx: 6.67\n", + "Kp Mín: 6.67\n", + "Kp Promedio: 6.67\n", + "Número de mediciones: 2\n", + "Categoría: G2 - Moderada\n", + "Eventos vinculados: 2\n", + "----------------------------------------\n", + "ID: 2024-05-10T15:00:00-GST-001\n", + "Inicio: 2024-05-10T15:00Z\n", + "Kp Máx: 9.0\n", + "Kp Mín: 6.67\n", + "Kp Promedio: 8.13\n", + "Número de mediciones: 13\n", + "Categoría: G5 - Fuerte\n", + "Eventos vinculados: 6\n", + "----------------------------------------\n", + "ID: 2024-05-12T21:00:00-GST-001\n", + "Inicio: 2024-05-12T21:00Z\n", + "Kp Máx: 6.33\n", + "Kp Mín: 5.67\n", + "Kp Promedio: 6.0\n", + "Número de mediciones: 3\n", + "Categoría: G2 - Moderada\n", + "Eventos vinculados: 2\n", + "----------------------------------------\n", + "ID: 2024-05-16T06:00:00-GST-001\n", + "Inicio: 2024-05-16T06:00Z\n", + "Kp Máx: 6.0\n", + "Kp Mín: 6.0\n", + "Kp Promedio: 6.0\n", + "Número de mediciones: 1\n", + "Categoría: G2 - Moderada\n", + "Eventos vinculados: 1\n", + "----------------------------------------\n", + "ID: 2024-05-17T18:00:00-GST-001\n", + "Inicio: 2024-05-17T18:00Z\n", + "Kp Máx: 6.0\n", + "Kp Mín: 6.0\n", + "Kp Promedio: 6.0\n", + "Número de mediciones: 1\n", + "Categoría: G2 - Moderada\n", + "Eventos vinculados: 2\n", + "----------------------------------------\n" + ] + } + ], + "source": [ + "def analizar_tormenta(tormenta):\n", + " \"\"\"\n", + " Analiza un evento de tormenta geomagnética.\n", + " \n", + " Parámetro:\n", + " tormenta (dict): un elemento de la lista retornada por el endpoint GST.\n", + " \n", + " Retorna:\n", + " dict con las claves: id, inicio, kp_max, kp_min, kp_promedio,\n", + " num_mediciones, categoria, eventos_vinculados.\n", + " \"\"\"\n", + " mediciones = tormenta[\"allKpIndex\"]\n", + "\n", + " kp_valores = [m[\"kpIndex\"] for m in mediciones]\n", + " resultado = {\n", + " \"id\": tormenta[\"gstID\"],\n", + " \"inicio\": tormenta[\"startTime\"],\n", + " \"kp_max\": max(kp_valores),\n", + " \"kp_min\": min(kp_valores),\n", + " \"kp_promedio\": round(sum(kp_valores) / len(kp_valores), 2),\n", + " \"num_mediciones\": len(mediciones),\n", + " \"categoria\": clasificar_kp(max(kp_valores)),\n", + " \"eventos_vinculados\": len(tormenta[\"linkedEvents\"] or []),\n", + " }\n", + " return resultado\n", + "\n", + "\n", + "# Aplicar a todas las tormentas e imprimir resumen\n", + "for tormenta in tormentas:\n", + " r = analizar_tormenta(tormenta)\n", + " # Hint: accede a cada clave del dict retornado con r[\"clave\"]\n", + " # TU CÓDIGO AQUÍ — imprime los campos de r de forma legible\n", + " print(f\"ID: {r['id']}\")\n", + " print(f\"Inicio: {r['inicio']}\")\n", + " print(f\"Kp Máx: {r['kp_max']}\")\n", + " print(f\"Kp Mín: {r['kp_min']}\")\n", + " print(f\"Kp Promedio: {r['kp_promedio']}\")\n", + " print(f\"Número de mediciones: {r['num_mediciones']}\")\n", + " print(f\"Categoría: {r['categoria']}\")\n", + " print(f\"Eventos vinculados: {r['eventos_vinculados']}\")\n", + " print(\"-\" * 40)" + ] + }, + { + "cell_type": "markdown", + "id": "conclusion-md", + "metadata": {}, + "source": [ + "---\n", + "## Pregunta final — Conclusiones (incluida en el punteo del Ejercicio 4)\n", + "\n", + "Basandote en los datos que obtuviste a lo largo del examen, escribe en la celda de abajo \n", + "una conclusion en tus propias palabras. Puedes responder estas preguntas como guia:\n", + "\n", + "- ¿Cual fue la tormenta mas intensa del periodo analizado y que tan severa fue segun la escala Kp?\n", + "- ¿Que patrones observas en los datos? (frecuencia, intensidad, eventos vinculados)\n", + "- ¿Que impacto podria haber tenido una tormenta de esa magnitud en la vida cotidiana?" + ] + }, + { + "cell_type": "markdown", + "id": "conclusion-answer", + "metadata": {}, + "source": [ + "**Conclusiones:**\n", + "\n", + "1. La tormenta mas intensa fue Inicio:2024-05-10T15:00Z con un Kp maximo de 9.00 y su clasificacion G5-Fuerte. Su kp es el valor maximo posible lo que implica que fue una tormenta geomagnetica extrema\n", + "2. Frecuencia :Se registraron 5 tormentas en un periodo de 15 dias, esto significa una alta activida geomagnetica. Tambien que hay una concentracion clara entre 10 y el 17 de mayor.\n", + "Intensidad: 4 de las 5 tormantas fueron G2 con kp de 6.00 a 6.67, solo hubo una tormenta intesa de clasificacion G5. Esto implica una actividad moderada\n", + "Eventos vinculados: La tormenta mas intensa tiene un mayor numero de mediciones que en total son 13 y de cantidad de eventos vinculados 6 en total. La tormentas moderadas tienen solamente entr 1 o 2 eventos.\n", + "3. Una tormenta nivel G5-Fuerte podria haber causado interrupciones en los sistemas de navegacion (GPS),apagones, Auroras visibles en latitudes inusualmente bajas y fallos en equipos " + ] + }, + { + "cell_type": "markdown", + "id": "sello-md", + "metadata": {}, + "source": [ + "---\n", + "## Sello de entrega\n", + "\n", + "Ejecuta la siguiente celda **como ultimo paso**, justo antes de guardar y subir el notebook.\n", + "\n", + "Realiza una consulta a la API de la ISS para registrar tu posicion geografica aproximada \n", + "al momento de entregar. Dado que la ISS se desplaza ~30 km cada 4 segundos, dos estudiantes \n", + "que entreguen en momentos distintos obtendran coordenadas completamente diferentes.\n", + "\n", + "> Este sello es **unico e irrepetible**: queda vinculado a tu carnet y al instante \n", + "> exacto en que ejecutaste la celda." + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "id": "sello-code", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Consultando posicion de la ISS...\n", + "\n", + "=======================================================\n", + " SELLO DE ENTREGA -- PARCIAL 2\n", + "=======================================================\n", + " Estudiante : Brandom Rodriguez\n", + " Carnet : 202506893\n", + " Fecha/Hora : 2026-04-25 00:40:26 UTC\n", + " ISS Latitud : -40.0224 deg\n", + " ISS Longitud : -61.6840 deg\n", + " ISS Hora UTC : 2026-04-25 00:40:24 UTC\n", + "=======================================================\n" + ] + } + ], + "source": [ + "from datetime import datetime, timezone\n", + "\n", + "# Obtener la posicion actual de la ISS\n", + "print(\"Consultando posicion de la ISS...\")\n", + "try:\n", + " r_iss = requests.get(\"http://api.open-notify.org/iss-now.json\", timeout=8)\n", + " r_iss.raise_for_status()\n", + " iss_data = r_iss.json()\n", + " iss_lat = float(iss_data[\"iss_position\"][\"latitude\"])\n", + " iss_lon = float(iss_data[\"iss_position\"][\"longitude\"])\n", + " iss_ts = iss_data[\"timestamp\"]\n", + " iss_hora = datetime.fromtimestamp(iss_ts, tz=timezone.utc).strftime(\"%Y-%m-%d %H:%M:%S UTC\")\n", + " iss_ok = True\n", + "except Exception as e:\n", + " iss_lat, iss_lon, iss_hora = 0.0, 0.0, \"no disponible\"\n", + " iss_ok = False\n", + " print(f\" Advertencia: no se pudo obtener la posicion ISS ({e})\")\n", + "\n", + "# Timestamp local del momento de entrega\n", + "ts_entrega = datetime.now(tz=timezone.utc).strftime(\"%Y-%m-%d %H:%M:%S UTC\")\n", + "\n", + "# Imprimir el sello\n", + "print()\n", + "print(\"=\" * 55)\n", + "print(\" SELLO DE ENTREGA -- PARCIAL 2\")\n", + "print(\"=\" * 55)\n", + "print(f\" Estudiante : {NOMBRE}\")\n", + "print(f\" Carnet : {CARNET}\")\n", + "print(f\" Fecha/Hora : {ts_entrega}\")\n", + "print(f\" ISS Latitud : {iss_lat:+.4f} deg\")\n", + "print(f\" ISS Longitud : {iss_lon:+.4f} deg\")\n", + "print(f\" ISS Hora UTC : {iss_hora}\")\n", + "print(\"=\" * 55)\n", + "\n", + "if not iss_ok:\n", + " print(\" Advertencia: sello generado sin datos de ISS (sin conexion).\")\n", + " print(\" Guarda el notebook de todas formas.\")" + ] + }, + { + "cell_type": "markdown", + "id": "cierre", + "metadata": {}, + "source": [ + "---\n", + "## Entrega\n", + "\n", + "1. Ejecuta la celda **Sello de entrega** (arriba)\n", + "2. Guarda el notebook: **Archivo → Guardar** (o `Ctrl+S`)\n", + "3. Verifica que **todas las celdas tienen output** (ejecuta: **Kernel → Restart & Run All**)\n", + "4. Sube el archivo a Github y copia el link en el campo de entrega en la U Virtual" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "6e9a231d-3229-4072-92d4-bac281a69979", + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "base", + "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.9" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/tareas/examen/import.py b/tareas/examen/import.py new file mode 100644 index 0000000..458084c --- /dev/null +++ b/tareas/examen/import.py @@ -0,0 +1,16 @@ +import os +import requests +import json +import time + +# Cargar la API key desde la variable de entorno. +# Si no está configurada, usa DEMO_KEY como respaldo (30 req/hora). +API_KEY = os.getenv("NASA_API_KEY", "").strip() or "DEMO_KEY" + +if API_KEY == "DEMO_KEY": + print(" Usando DEMO_KEY - limite: 30 solicitudes/hora") + print(" Configura NASA_API_KEY para mayor limite (ver instrucciones arriba).") +else: + print(f" API key cargada: {API_KEY[:4]}{'*' * (len(API_KEY) - 4)}") + +print("\nLibrerias importadas correctamente ") diff --git a/tareas/prueba.tex b/tareas/prueba.tex new file mode 100644 index 0000000..4fbd3ba --- /dev/null +++ b/tareas/prueba.tex @@ -0,0 +1,5 @@ +\documentclass[options]{article} + +\begin{document} +hola mundo! +\end{document} \ No newline at end of file diff --git a/tareas/python/1.Hola Mundo y Print()/Ejercicio 1a.py b/tareas/python/1.Hola Mundo y Print()/Ejercicio 1a.py new file mode 100644 index 0000000..e34f410 --- /dev/null +++ b/tareas/python/1.Hola Mundo y Print()/Ejercicio 1a.py @@ -0,0 +1,2 @@ +print("Nombre: Brandom Aroldo Rodriguez Gonzalez") +print("Cartnet: 202506893") \ No newline at end of file diff --git a/tareas/python/1.Hola Mundo y Print()/Ejercicio 1b.py b/tareas/python/1.Hola Mundo y Print()/Ejercicio 1b.py new file mode 100644 index 0000000..ce39771 --- /dev/null +++ b/tareas/python/1.Hola Mundo y Print()/Ejercicio 1b.py @@ -0,0 +1,3 @@ +print("Hola ", end="") +print("desde ", end="") +print("python", end="") \ No newline at end of file diff --git a/tareas/python/10. Manejo de errores/Ejercicio 10a.py b/tareas/python/10. Manejo de errores/Ejercicio 10a.py new file mode 100644 index 0000000..62575fe --- /dev/null +++ b/tareas/python/10. Manejo de errores/Ejercicio 10a.py @@ -0,0 +1,13 @@ +def entero(n): + try: + resultado = int(n) + return resultado + except ValueError: + print("Error: No se puede convertir a entero") + return None + finally: + print(f"[intento con: {n}]") +print(entero("42")) +print(entero("3.14")) +print(entero("hola")) +print(entero(100)) \ No newline at end of file diff --git a/tareas/python/10. Manejo de errores/Ejercicio 10b.py b/tareas/python/10. Manejo de errores/Ejercicio 10b.py new file mode 100644 index 0000000..2a61a67 --- /dev/null +++ b/tareas/python/10. Manejo de errores/Ejercicio 10b.py @@ -0,0 +1,15 @@ +def v_n(n): + if not isinstance(n, int): + raise TypeError("La edad debe ser un entero") + if n < 0 or n > 150: + raise ValueError("La edad debe estar entre 0 y 150") + return True +x = [25, -5, 200, "veinte"] +for v in x: + try: + y = v_n(v) + print(f"{v} -> Edad valida:", y) + except TypeError as te: + print(f"{v} -> TypeError:", te) + except ValueError as ve: + print(f"{v} -> ValueError:", ve) \ No newline at end of file diff --git a/tareas/python/2.Variables y tipos de datos/Ejercicio 2a.py b/tareas/python/2.Variables y tipos de datos/Ejercicio 2a.py new file mode 100644 index 0000000..e8203ef --- /dev/null +++ b/tareas/python/2.Variables y tipos de datos/Ejercicio 2a.py @@ -0,0 +1,10 @@ +#variables +Nombre= "Brandom Aroldo Rodriguez Gonzalez" +Edad= int(21) +Promedio = float(72) +activo= bool(True) + +print("Nombre "+ str(Nombre) + type(Nombre).__name__) +print("Edad " + str(Edad) + type(Edad).__name__) +print("Promedio " + str(Promedio)+ type(Promedio).__name__) +print("activo " + str(activo) + type(activo).__name__) diff --git a/tareas/python/2.Variables y tipos de datos/Ejercicio 2b.py b/tareas/python/2.Variables y tipos de datos/Ejercicio 2b.py new file mode 100644 index 0000000..0838f46 --- /dev/null +++ b/tareas/python/2.Variables y tipos de datos/Ejercicio 2b.py @@ -0,0 +1,7 @@ +x= int(10) +y= int(20) +z= int(30) + +print(f"x=",x, end=" ") +print(f"y=",y, end=" ") +print(f"z=",z, end=" ") \ No newline at end of file diff --git "a/tareas/python/3.Operaciones aritm\303\251ticas/Ejercicio 3a.py" "b/tareas/python/3.Operaciones aritm\303\251ticas/Ejercicio 3a.py" new file mode 100644 index 0000000..4b78f45 --- /dev/null +++ "b/tareas/python/3.Operaciones aritm\303\251ticas/Ejercicio 3a.py" @@ -0,0 +1,5 @@ +a = int(23) +b = int(7) +print("Diviion: " +str(a/b)) +print("Residuo: " +str(a%b)) +print("a^b: " + str(a**b)) \ No newline at end of file diff --git "a/tareas/python/3.Operaciones aritm\303\251ticas/Ejercicio 3b.py" "b/tareas/python/3.Operaciones aritm\303\251ticas/Ejercicio 3b.py" new file mode 100644 index 0000000..074d258 --- /dev/null +++ "b/tareas/python/3.Operaciones aritm\303\251ticas/Ejercicio 3b.py" @@ -0,0 +1,9 @@ +import math +x=int(144) +print("La raiz cuadrada de 144 es: " + str( math.sqrt(x))) +y=int(7.3) +print("El techo de 7.3 es: " + str(math.ceil(y))) +z=int(7.9) +print("El piso de 7.9: " + str(math.floor(z))) +A= math.pi +print("El valor de pi redondeado a 4 decimales: " + str(round(A,4)) ) \ No newline at end of file diff --git "a/tareas/python/4.Strings y m\303\251todos \303\272tiles/Ejercicio 4a.py" "b/tareas/python/4.Strings y m\303\251todos \303\272tiles/Ejercicio 4a.py" new file mode 100644 index 0000000..5542dd6 --- /dev/null +++ "b/tareas/python/4.Strings y m\303\251todos \303\272tiles/Ejercicio 4a.py" @@ -0,0 +1,13 @@ +cadena= " fisica y matematicas " + +x=cadena.strip() + +print("Paso 1: " + x) + +y=x.upper() + +print("Paso 2: " + y) + +z=y.replace("Y","&") + +print("Paso 3: " + z) \ No newline at end of file diff --git "a/tareas/python/4.Strings y m\303\251todos \303\272tiles/Ejercicio 4b.py" "b/tareas/python/4.Strings y m\303\251todos \303\272tiles/Ejercicio 4b.py" new file mode 100644 index 0000000..fa00c31 --- /dev/null +++ "b/tareas/python/4.Strings y m\303\251todos \303\272tiles/Ejercicio 4b.py" @@ -0,0 +1,10 @@ +colores_str = "rojo-verde-azul-amarillo" +x = colores_str.split("-") + +print("paso 1: "+ str(x)) + +y=" | ".join(x) + +print("Paso 2: " + str(y)) + +print("verde" in y) \ No newline at end of file diff --git a/tareas/python/5.Listas/Ejercicio 5a.py b/tareas/python/5.Listas/Ejercicio 5a.py new file mode 100644 index 0000000..95b9337 --- /dev/null +++ b/tareas/python/5.Listas/Ejercicio 5a.py @@ -0,0 +1,6 @@ +x = ["Calculo", "Fisica", "Programacion", "Algebra"] +x.append("Estadistica") +x.insert(1, "Quimica") +x.remove("Algebra") +print("Lista final:", x) +print("Longitud:", len(x)) \ No newline at end of file diff --git a/tareas/python/5.Listas/Ejercicio 5b.py b/tareas/python/5.Listas/Ejercicio 5b.py new file mode 100644 index 0000000..5ad86d5 --- /dev/null +++ b/tareas/python/5.Listas/Ejercicio 5b.py @@ -0,0 +1,11 @@ +notas = [78, 92, 65, 88, 74, 95, 61, 83] + +minimo = min(notas) +maximo = max(notas) +suma = sum(notas) +promedio = suma / len(notas) + +print(f"Minimo: {minimo}") +print(f"Maximo: {maximo}") +print(f"Suma: {suma}") +print(f"Promedio: {promedio:.2f}") \ No newline at end of file diff --git a/tareas/python/6.Diccionarios/Ejercicio 6a.py b/tareas/python/6.Diccionarios/Ejercicio 6a.py new file mode 100644 index 0000000..b83e79b --- /dev/null +++ b/tareas/python/6.Diccionarios/Ejercicio 6a.py @@ -0,0 +1,11 @@ + +curso = { + "nombre": "Programación", + "codigo": "1505", + "creditos": 10, + "activo": True +} + +curso["estudiantes"] = 35 +print("Creditos:", curso.get("creditos")) +print("Salon:", curso.get("salon", "Sin asignar")) \ No newline at end of file diff --git a/tareas/python/6.Diccionarios/Ejercicio 6b.py b/tareas/python/6.Diccionarios/Ejercicio 6b.py new file mode 100644 index 0000000..8e66483 --- /dev/null +++ b/tareas/python/6.Diccionarios/Ejercicio 6b.py @@ -0,0 +1,11 @@ + +curso = { + "nombre": "Programacion", + "codigo": "1505", + "creditos": 10, + "activo": True, + "estudiantes": 35 +} + +for clave, valor in curso.items(): + print(f"{clave:12} : {valor}") \ No newline at end of file diff --git a/tareas/python/7.Condicionales/Ejercicio 7a.py b/tareas/python/7.Condicionales/Ejercicio 7a.py new file mode 100644 index 0000000..5a09dcb --- /dev/null +++ b/tareas/python/7.Condicionales/Ejercicio 7a.py @@ -0,0 +1,15 @@ +def clasificar_imc(imc): + if imc<=18: + return "Bajo peso" + elif 19<=imc<=25 : + return "Normal" + elif 26<=imc<=29: + return "Sobrepeso" + elif 30<=imc: + return "Obesidad" +try: + imc_usuario = float(input("Ingresa tu IMC: ")) + resultado = clasificar_imc(imc_usuario) + print(f"Clasificacion: {resultado}") +except ValueError: + print("Ingresa un número valido.") \ No newline at end of file diff --git a/tareas/python/7.Condicionales/Ejercicio 7b.py b/tareas/python/7.Condicionales/Ejercicio 7b.py new file mode 100644 index 0000000..f04bb11 --- /dev/null +++ b/tareas/python/7.Condicionales/Ejercicio 7b.py @@ -0,0 +1,5 @@ +numeros = [4, 7, 0] + +for n in numeros: + resultado = "par" if n % 2 == 0 else "impar" + print(f"{n} es {resultado}") \ No newline at end of file diff --git a/tareas/python/8.Ciclos/Ejercicio 8a.py b/tareas/python/8.Ciclos/Ejercicio 8a.py new file mode 100644 index 0000000..2e1b4c0 --- /dev/null +++ b/tareas/python/8.Ciclos/Ejercicio 8a.py @@ -0,0 +1,4 @@ +planetas = ["Mercurio", "Venus", "Tierra", "Marte", "Jupiter", "Saturno", "Urano", "Neptuno"] + +for i, planeta in enumerate(planetas, start=1): + print(f"[{i}] {planeta}") \ No newline at end of file diff --git a/tareas/python/8.Ciclos/Ejercicio 8b.py b/tareas/python/8.Ciclos/Ejercicio 8b.py new file mode 100644 index 0000000..4f2c5a5 --- /dev/null +++ b/tareas/python/8.Ciclos/Ejercicio 8b.py @@ -0,0 +1,5 @@ +i = 1 + +while i <= 10: + print(f"7 x {i} = {7 * i}") + i += 1 \ No newline at end of file diff --git a/tareas/python/8.Ciclos/Ejercicio 8c.py b/tareas/python/8.Ciclos/Ejercicio 8c.py new file mode 100644 index 0000000..c308848 --- /dev/null +++ b/tareas/python/8.Ciclos/Ejercicio 8c.py @@ -0,0 +1,2 @@ +print([x**3 for x in range(1, 9)]) +print([x for x in range(1, 31) if x % 3 == 0 and x % 9 != 0]) \ No newline at end of file diff --git a/tareas/python/9.Funciones/Ejercicio 9a.py b/tareas/python/9.Funciones/Ejercicio 9a.py new file mode 100644 index 0000000..8340514 --- /dev/null +++ b/tareas/python/9.Funciones/Ejercicio 9a.py @@ -0,0 +1,11 @@ +def convertir_t(g, e="C"): + if e == "C": + return g * 9/5 + 32 + elif e == "F": + return (g - 32) * 5/9 + else: + return "Escala no válida" +print("100°C ->", convertir_t(100, "C"), "°F") +print("0°C ->", convertir_t(0, "C"), "°F") +print("32°F ->", convertir_t(32, "F"), "°C") +print("212°F ->", convertir_t(212, "F"), "°C") \ No newline at end of file diff --git a/tareas/python/9.Funciones/Ejercicio 9b.py b/tareas/python/9.Funciones/Ejercicio 9b.py new file mode 100644 index 0000000..32f3975 --- /dev/null +++ b/tareas/python/9.Funciones/Ejercicio 9b.py @@ -0,0 +1,10 @@ +def r_l(l): + minimo = min(l) + maximo = max(l) + promedio = sum(l) / len(l) + return minimo, maximo, promedio +n = [12, 45, 7, 89, 34, 56, 23] +minimo, maximo, promedio = r_l(n) +print("Minimo:", minimo) +print("Maximo:", maximo) +print("Promedio:", promedio) \ No newline at end of file diff --git a/tareas/python/9.Funciones/Ejercicio 9c.py b/tareas/python/9.Funciones/Ejercicio 9c.py new file mode 100644 index 0000000..629be9b --- /dev/null +++ b/tareas/python/9.Funciones/Ejercicio 9c.py @@ -0,0 +1,9 @@ +def fibonacci(n): + if n == 0: + return 0 + elif n == 1: + return 1 + else: + return fibonacci(n-1) + fibonacci(n-2) +for i in range(11): + print(f"fibonacci({i}) = {fibonacci(i)}") \ No newline at end of file diff --git a/tareas/python/Ejercicio integrador/Ejercicio integrador.py b/tareas/python/Ejercicio integrador/Ejercicio integrador.py new file mode 100644 index 0000000..ef67b33 --- /dev/null +++ b/tareas/python/Ejercicio integrador/Ejercicio integrador.py @@ -0,0 +1,32 @@ +def a(e): + aprobados = 0 + reprobados = 0 + print(f"{'Nombre':<15} {'Promedio':<10} {'Estado'}") + for alumno in e: + nombre = alumno["nombre"] + n = alumno["notas"] + if n: + p = sum(n) / len(n) + else: + p = None + if p is None: + estado = "Sin notas" + elif p >= 61: + estado = "Aprobado" + aprobados += 1 + else: + estado = "Reprobado" + reprobados += 1 + p_str = f"{p:.2f}" if p is not None else "N/A" + print(f"{nombre:<15} {p_str:<10} {estado}") + print(f"Aprobados: {aprobados}") + print(f"Reprobados: {reprobados}") +c = [ + {"nombre": "Ana Lopez", "notas": [85, 90, 78, 92]}, + {"nombre": "Carlos Ruiz", "notas": [55, 48, 60, 52]}, + {"nombre": "Maria Paz", "notas": [70, 75, 68, 80]}, + {"nombre": "Luis Gomez", "notas": [95, 98, 100, 92]}, + {"nombre": "Sara Diaz", "notas": [40, 55, 50, 45]}, + {"nombre": "Pedro Alva", "notas": []}, +] +a(c) \ No newline at end of file diff --git a/tareas/tarea_3/busqueda_dos_en_dos/busqueda_dos_en_dos.cpp b/tareas/tarea_3/busqueda_dos_en_dos/busqueda_dos_en_dos.cpp new file mode 100644 index 0000000..64590b6 --- /dev/null +++ b/tareas/tarea_3/busqueda_dos_en_dos/busqueda_dos_en_dos.cpp @@ -0,0 +1,42 @@ +#include +#include +using namespace std; +int busquedaDosEnDos(const vector& lista, int objetivo) { + int n = lista.size(); + for (int i = 0; i < n; i += 2) { + if (lista[i] == objetivo) { + return i; + } + if (i + 1 < n && lista[i + 1] == objetivo) { + return i + 1; + } + } + return -1; +} +int main() { + vector lista; + int n, x; + cout << "ingrese la cantidad de elementos: "; + cin >> n; + cout << "ingrese los elementos:\n"; + for (int i = 0; i < n; i++) { + cin >> x; + lista.push_back(x); + } + char continuar = 's'; + while (continuar == 's' || continuar == 'S') { + int objetivo; + cout << "\ningrese el numero a buscar: "; + cin >> objetivo; + int resultado = busquedaDosEnDos(lista, objetivo); + if (resultado != -1) { + cout << "objetivo encontrado en : " << resultado << endl; + } else { + cout << "objetivo no existe" << endl; + } + + cout << "\n desea buscar otro numero? (s/n): "; + cin >> continuar; + } + return 0; +} \ No newline at end of file diff --git a/tareas/tarea_3/busqueda_dos_en_dos/busqueda_dos_en_dos.exe b/tareas/tarea_3/busqueda_dos_en_dos/busqueda_dos_en_dos.exe new file mode 100644 index 0000000..8c408ff Binary files /dev/null and b/tareas/tarea_3/busqueda_dos_en_dos/busqueda_dos_en_dos.exe differ diff --git a/tareas/tarea_3/busqueda_lineal/busqueda_lineal.cpp b/tareas/tarea_3/busqueda_lineal/busqueda_lineal.cpp new file mode 100644 index 0000000..d87031e --- /dev/null +++ b/tareas/tarea_3/busqueda_lineal/busqueda_lineal.cpp @@ -0,0 +1,47 @@ +#include +using namespace std; + +// --------- BUSQUEDA LINEAL --------- +int busquedaLineal(int arr[], int n, int valor) { + for (int i = 0; i < n; i++) { + if (arr[i] == valor) { + return i; // retorna la posición donde se encontró + } + } + return -1; // no encontrado +} + +// --------- MAIN --------- +int main() { + int n, valor; + char repetir; + + do { + cout << "\nCantidad de datos: "; + cin >> n; + + int arr[1000]; + + cout << "Ingrese los datos:\n"; + for (int i = 0; i < n; i++) { + cin >> arr[i]; + } + + cout << "\nIngrese el valor a buscar: "; + cin >> valor; + + int resultado = busquedaLineal(arr, n, valor); + + if (resultado != -1) { + cout << "Valor encontrado en la posicion: " << resultado << endl; + } else { + cout << "Valor no encontrado.\n"; + } + + cout << "\nDesea repetir? (s/n): "; + cin >> repetir; + + } while (repetir == 's' || repetir == 'S'); + + return 0; +} \ No newline at end of file diff --git a/tareas/tarea_3/busqueda_lineal/busqueda_lineal.exe b/tareas/tarea_3/busqueda_lineal/busqueda_lineal.exe new file mode 100644 index 0000000..05e7485 Binary files /dev/null and b/tareas/tarea_3/busqueda_lineal/busqueda_lineal.exe differ diff --git a/tareas/tarea_3/contar_hasta_10/contar_hasta_10.cpp b/tareas/tarea_3/contar_hasta_10/contar_hasta_10.cpp new file mode 100644 index 0000000..32ca739 --- /dev/null +++ b/tareas/tarea_3/contar_hasta_10/contar_hasta_10.cpp @@ -0,0 +1,9 @@ +#include +using namespace std; + +int main() { + for (int i = 1; i <= 10; i++) { + cout << i << "\n"; + } + return 0; +} \ No newline at end of file diff --git a/tareas/tarea_3/contar_hasta_10/contar_hasta_10.exe b/tareas/tarea_3/contar_hasta_10/contar_hasta_10.exe new file mode 100644 index 0000000..6167ba9 Binary files /dev/null and b/tareas/tarea_3/contar_hasta_10/contar_hasta_10.exe differ diff --git a/tareas/tarea_3/contar_vocales/contar_vocales.cpp b/tareas/tarea_3/contar_vocales/contar_vocales.cpp new file mode 100644 index 0000000..99a010d --- /dev/null +++ b/tareas/tarea_3/contar_vocales/contar_vocales.cpp @@ -0,0 +1,27 @@ +#include +using namespace std; +int contarVocales(string texto) { + int contar = 0; + for (char x : texto) { + x = tolower(x); + if (x == 'a' || x == 'e' || x == 'i' || x == 'o' || x == 'u') { + contar++; + } + } + return contar; +} +int main() { + string oracion; + char continuar; + do { + cout << "ingrese una oracion: "; + getline(cin, oracion); + int total = contarVocales(oracion); + cout << "total de vocales: " << total << endl; + cout << "desea ingresar otra oracion? (s/n): "; + cin >> continuar; + cin.ignore(); + } while (continuar == 's' || continuar == 'S'); + cout << "programa terminado." << endl; + return 0; +} \ No newline at end of file diff --git a/tareas/tarea_3/contar_vocales/contar_vocales.exe b/tareas/tarea_3/contar_vocales/contar_vocales.exe new file mode 100644 index 0000000..28481c4 Binary files /dev/null and b/tareas/tarea_3/contar_vocales/contar_vocales.exe differ diff --git a/tareas/tarea_3/numero_primo/numero_primo.cpp b/tareas/tarea_3/numero_primo/numero_primo.cpp new file mode 100644 index 0000000..524ee00 --- /dev/null +++ b/tareas/tarea_3/numero_primo/numero_primo.cpp @@ -0,0 +1,29 @@ +#include +using namespace std; +bool esprimo(int x) { + if (x <= 1) return false; + if (x == 2) return true; + for (int i = 2; i * i <= x; i++) { + if (x % i == 0) { + return false; + } + } + return true; +} +int main() { + int numero; + char continuar; + do { + cout << "ingrese un numero: "; + cin >> numero; + if (esprimo(numero)) { + cout << "primo" << endl; + } else { + cout << "no primo" << endl; + } + cout << "desea ingresar otro numero? (s/n): "; + cin >> continuar; + } while (continuar == 's' || continuar == 'S'); + cout << "programa terminado." << endl; + return 0; +} \ No newline at end of file diff --git a/tareas/tarea_3/numero_primo/numero_primo.exe b/tareas/tarea_3/numero_primo/numero_primo.exe new file mode 100644 index 0000000..18b580b Binary files /dev/null and b/tareas/tarea_3/numero_primo/numero_primo.exe differ diff --git a/tareas/tarea_3/ordenamiento/ordenamiento.cpp b/tareas/tarea_3/ordenamiento/ordenamiento.cpp new file mode 100644 index 0000000..a842863 --- /dev/null +++ b/tareas/tarea_3/ordenamiento/ordenamiento.cpp @@ -0,0 +1,99 @@ +#include +using namespace std; +// bubble +void bubble(int arr[], int n) { + for (int x = 0; x < n - 1; x++) { + for (int y = 0; y < n - x - 1; y++) { + if (arr[y] > arr[y + 1]) { + swap(arr[y], arr[y + 1]); + } + } + } +} +// seleccion +void Selection(int arr[], int n) { + for (int x = 0; x < n - 1; x++) { + int min = x; + for (int y = x + 1; y < n; y++) { + if (arr[y] < arr[min]) { + min = y; + } + } + swap(arr[x], arr[min]); + } +} +// merge sort +void merge(int arr[], int start, int medium, int end) { + int x = start, y = medium + 1, z = 0; + int temp[100]; + while (x <= medium && y <= end) { + if (arr[x] < arr[y]) { + temp[z++] = arr[x++]; + } else { + temp[z++] = arr[y++]; + } + } + while (x <= medium) { + temp[z++] = arr[x++]; + } + while (y <= end) { + temp[z++] = arr[y++]; + } + for (int x = start, y = 0; x <= end; x++, y++) { + arr[x] = temp[y]; + } +} +void mergesort(int arr[], int start, int end) { + if (start < end) { + int medium = (start + end) / 2; + mergesort(arr, start, medium); + mergesort(arr, medium + 1, end); + merge(arr, start, medium, end); + } +} +// --------- MOSTRAR --------- +void mostrar(int arr[], int n) { + for (int x = 0; x < n; x++) { + cout << arr[x] << " "; + } + cout << endl; +} +// --------- MAIN --------- +int main() { + int opcion, n; + char repetir; + do { + cout << "\nCantidad de datos: "; + cin >> n; + int arr[1000]; + cout << "Ingrese los datos:\n"; + for (int x = 0; x < n; x++) { + cin >> arr[x]; + } + cout << "\nMetodos de ordenamiento:\n"; + cout << "1. bubble\n"; + cout << "2. Selection\n"; + cout << "3. Merge Sort\n"; + cout << "Elija una opcion: "; + cin >> opcion; + switch (opcion) { + case 1: + bubble(arr, n); + break; + case 2: + Selection(arr, n); + break; + case 3: + mergesort(arr, 0, n - 1); + break; + default: + cout << "Opcion invalida\n"; + continue; + } + cout << "\nArreglo ordenado:\n"; + mostrar(arr, n); + cout << "\nDesea repetir? (s/n): "; + cin >> repetir; + } while (repetir == 's' || repetir == 'S'); + return 0; +} \ No newline at end of file diff --git a/tareas/tarea_3/ordenamiento/ordenamiento.exe b/tareas/tarea_3/ordenamiento/ordenamiento.exe new file mode 100644 index 0000000..0f2702b Binary files /dev/null and b/tareas/tarea_3/ordenamiento/ordenamiento.exe differ diff --git a/tareas/tarea_3/suma_digitos/suma_digitos.cpp b/tareas/tarea_3/suma_digitos/suma_digitos.cpp new file mode 100644 index 0000000..dcd22a8 --- /dev/null +++ b/tareas/tarea_3/suma_digitos/suma_digitos.cpp @@ -0,0 +1,21 @@ +#include +#include +using namespace std; +int main() { + char continuar; + do { + int x, suma = 0; + cout << " ingresa un numero entero: "; + cin >> x; + x = abs(x); + while (x > 0) { + suma += x % 10; + x /= 10; + } + cout << "La suma de los digitos es: " << suma << endl; + cout << "deseas volverlo a intentar? (s/n): "; + cin >> continuar; + } while (continuar == 's' || continuar == 'S'); + cout << "programa terminado." << endl; + return 0; +} \ No newline at end of file diff --git a/tareas/tarea_3/suma_digitos/suma_digitos.exe b/tareas/tarea_3/suma_digitos/suma_digitos.exe new file mode 100644 index 0000000..85c9728 Binary files /dev/null and b/tareas/tarea_3/suma_digitos/suma_digitos.exe differ