From 7044bcbb06a4d060e0394cfa235d5118f66451c0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nacho=20L=C3=B3pez?= <145539062+KrilinZ@users.noreply.github.com> Date: Mon, 3 Aug 2026 14:14:05 +0200 Subject: [PATCH 1/2] docs(readme): rewrite for clarity, SEO and AI answer engines --- README.md | 209 +++++++++++++++++++++++++++++++++++++++++++++--------- 1 file changed, 176 insertions(+), 33 deletions(-) diff --git a/README.md b/README.md index de2fda3..18f53b8 100644 --- a/README.md +++ b/README.md @@ -1,64 +1,207 @@ -# Welcome to Numpy exercise tutorial +
-By @alesanchezr and other contributors at 4Geeks Academy. - +# Numpy Tutorial Exercises -NumPy (and Pandas) are the #1 libraries for Machine Learning, there is no way you can do anything without them. +[![Certified by 4Geeks](https://img.shields.io/badge/4Geeks-certified%20tutorial-2563eb)](https://4geeks.com) +[![Autograded with LearnPack](https://img.shields.io/badge/LearnPack-autograded-2563eb)](https://learnpack.co) +[![Open in Codespaces](https://img.shields.io/badge/Open%20in-Codespaces-fb5a1f)](https://codespaces.new/?repo=4GeeksAcademy/numpy-tutorial-exercises) -This interactive tutorial will help you become familiar with it, master the most used functionalities, and help you clean up your first datasets. +🇪🇸 [Leer en español](https://github.com/4GeeksAcademy/numpy-tutorial-exercises/blob/HEAD/README.es.md) · 🇬🇧 [Read in English](https://github.com/4GeeksAcademy/numpy-tutorial-exercises/blob/HEAD/README.md) -- NumPy documentation. -- Vectors. -- Matrixes. -- Random, Mean Values. +![Cover of the interactive NumPy tutorial, showing the words Learn Python Numpy interactive next to the blue and light blue NumPy cube logo on a black background](https://raw.githubusercontent.com/4GeeksAcademy/numpy-tutorial-exercises/master/.learn/assets/preview.jpeg) -> Note: The entire tutorial is 👆 interactive, ✅ auto-graded and with 📹 video tutorials. +
+ -These exercises were built in collaboration; we need you! If you find any bugs or misspellings, please contribute and report them. +This LearnPack tutorial teaches NumPy through 21 exercises: one welcome page plus 20 auto-graded challenges on array creation, indexing, slicing, reshaping and basic statistics. You write every answer in a single `app.py` file and 53 pytest checks grade it. It drills `zeros`, `ones`, `arange`, `reshape`, `eye`, `pad`, `diag`, `nonzero`, `random`, `max` and `mean`. Estimated time: 10 hours, intermediate level. -## One click installation (recommended): +## 📋 About this tutorial + +- **Difficulty:** intermediate +- **Estimated duration:** 10 hours +- **Language:** Python 3 +- **Technologies:** Python, NumPy 1.24.2, pytest, LearnPack +- **Exercises:** 21 folders — 1 welcome page + 20 with automatic grading +- **Grading:** `incremental` mode, powered by LearnPack and pytest (53 `@pytest.mark.it` checks) +- **Available in:** English (`README.md`) and Spanish (`README.es.md`) inside every exercise -You can open these exercises in just a few seconds by clicking: [Open in Codespaces](https://codespaces.new/?repo=4GeeksAcademy/numpy-tutorial-exercises) (recommended) or [Open in Gitpod](https://gitpod.io#https://github.com/4GeeksAcademy/numpy-tutorial-exercises.git). + -> Once you have VSCode open the LearnPack exercises should start automatically. If exercises don't run automatically you can try typing on your terminal: `$ learnpack start` +## 🎯 What will you learn? +NumPy is the array library that Pandas, scikit-learn and almost every scientific Python package are built on top of. This tutorial does not explain the theory of vector spaces: it makes you type the API until it sticks. Each exercise is one or two lines of code, so in a single sitting you touch the functions you will use every day. +By the end you will be comfortable with: -## Local Installation +- Importing the library the canonical way, `import numpy as np`, and inspecting the installed build with `np.__version__` and `np.show_config()`. +- Reading the documentation without leaving Python, using `np.info(np.add)`. +- Creating arrays from nothing: `np.zeros()`, `np.ones()`, `np.eye()`, `np.arange()` and `np.array()`. +- Measuring what an array costs in RAM by multiplying its `.itemsize` by its `.size` (a vector of 10 floats takes 80 bytes). +- Editing values by position and by slice: `arr[4] = 1`, `matrix[1:-1, 1:-1] = 0`, `arr[::-1]`, `matrix[1::2, ::2] = 1`. +- Changing the shape of an array with `reshape()`, turning a 9-element vector into a 3×3 matrix. +- Searching inside an array with `np.nonzero()` and reading the tuple of index arrays it gives you back. +- Generating random data with `np.random.random()` and summarising it with `.max()` and `.mean()`. +- Growing a matrix with `np.pad()` and pulling out its main diagonal with `np.diag()`. +- The edge cases that bite everyone: `np.nan == np.nan` is `False`, `np.nan in set([np.nan])` is `True`, and `0.3 == 3 * 0.1` is `False`. -1. Clone or download this repository. +The exercises really are that short. This is the kind of slicing the last one, an 8×8 checkerboard, is built out of: -2. Make sure you have [LearnPack](https://learnpack.co) installed, node.js version 14+, and Python version 3+. This is the command to install LearnPack: +```python +import numpy as np -```bash -$ npm i @learnpack/learnpack -g && learnpack plugins:install @learnpack/python -``` +matrix = np.zeros((6, 6)) -3. Start the tutorial/exercises by running the following commands at the same level where your learn.json file is: +matrix[::2, 1::2] = 1 # ones on the even rows, odd columns -```bash -$ pip3 install pytest==6.2.5 mock pytest-testdox toml numpy==1.24.2 pandas -$ learnpack start +print(matrix[0]) # [0. 1. 0. 1. 0. 1.] ``` -> Note: The exercises have automatic grading, but it's very rigid and strict, my recommendation is to not take the tests too serious and use them only as a suggestion, or you may get frustrated. +## 👀 What will you build? - +There is no final project. You build one file, `app.py`, created in the first exercise and rewritten in every step afterwards. These are the 21 folders inside `.learn/exercises`, in order: + +1. **`000` Welcome** — reading only, with no test: what NumPy is, why it is used, plus links to the official docs and a video. +2. **`001` Create Entry File** — create `app.py` in the root of the project. The single test only checks that the file exists. +3. **`002` Import NumPy** — import the library under the alias `np`. +4. **`003` NumPy Version** — print the installed version through `np.__version__`. +5. **`004` Your First Vector** — print a null vector of size 10 built with `np.zeros()`. +6. **`005` Array Memory Size** — print `80`, the memory that vector occupies, obtained from `.itemsize` and `.size`. +7. **`006` NumPy Documentation** — print the documentation of `np.add()` with `np.info()`. +8. **`007` Change Vector Values** — a null vector of size 10 whose fifth element (index `4`) is `1`. +9. **`008` Vector Ranging Values** — a vector with every integer from 10 to 49, built with `np.arange()`. +10. **`009` Reverse Vector** — the integers from 0 to 9 printed backwards using `array[::-1]`. +11. **`010` Matrix with Ranging Values** — the numbers 0 to 8 turned into a 3×3 matrix with `reshape()`. +12. **`011` Find Indexes of Non Zero Elements** — `np.nonzero()` over `[1,2,0,0,4,0]`, printing `(array([0, 1, 4]),)`. +13. **`012` Identity Matrix** — a 3×3 identity matrix created with `np.eye()`. +14. **`013` Random Values Array** — a variable named `arr` holding an array of 3 random values. +15. **`014` Minimum and Maximum** — `arr` with 10 random values, printing the largest one with `.max()`. +16. **`015` Mean Value** — `arr` with 10 random values, printing its average with `.mean()`. +17. **`016` Array Border** — a 5×5 matrix of ones whose centre is set to zero with `matrix[1:-1, 1:-1]`. +18. **`017` Add Border to Array** — a 3×3 matrix of ones wrapped in a border of zeros with `np.pad()`. +19. **`018` Result of Expressions** — print the six results of the `nan` and `inf` comparisons: `nan`, `False`, `False`, `nan`, `True`, `False`. +20. **`019` Diagonal** — print `[0 4 8]`, the diagonal of a 3×3 matrix, using `np.diag()`. +21. **`020` Checkerboard Pattern** — an 8×8 matrix filled with a checkerboard of zeros and ones. + +## 🎓 What do you need before starting? + +The tutorial is registered as **intermediate**, and the reason is Python, not mathematics. There is nothing here beyond arithmetic: the "matrices" are grids of numbers. What you do need is: + +- **Comfortable Python basics** — variables, `print()`, lists and, above all, slice notation. Half the exercises are solved with a slice like `[::-1]`, `[1:-1, 1:-1]` or `[1::2, ::2]`. +- **No previous NumPy at all.** Exercise `002` starts from `import numpy as np`, and every function is introduced with a hint and a link to its page on numpy.org. +- **A Python 3 environment with NumPy and pytest.** If you open the repository in Codespaces, the dev container installs Python 3.10, `numpy==1.24.2` and `pytest==6.2.5` for you. Working locally you install them yourself. +- **Node.js 22** only if you run the exercises on your own machine, because LearnPack is a Node command line tool. + +## ✅ How does the automatic grading work? + +20 of the 21 folders ship a `test.py` file, and together they hold 53 checks written with `@pytest.mark.it("...")`, so each failure tells you in plain English what was expected. Grading mode is `incremental`: the exercises build on one another and all of them read the same `app.py` sitting in the root of the repository, not inside the exercise folder. + +There are four kinds of check, and knowing which one you are facing saves a lot of time: + +- **Output checks** capture what your program prints using pytest's `capsys` fixture. Up to exercise `012` they only require the expected text to appear somewhere in your output, but from `015` to `020` they compare the whole console output with `==`, character by character. +- **Source checks** open `app.py` and search for the function you were told to use: `zeros(`, `ones(`, `arange(`, `reshape(`, `eye(`, `pad(`, `diag(`, `nonzero`, `array`, `random(`, `max(`, `mean(`, `info(`, `itemsize`, `size`. +- **Anti-hardcoding checks** run a regular expression that fails if the expected result is written literally in your file. Eight exercises have one. +- **Import checks** in `013`, `014` and `015` run `from app import arr`, so `arr` has to exist as a variable at the top level of the module. + +Run the tests from the LearnPack interface after editing `app.py`, and read the description of the failing check before touching your code. + +## 💡 What mistakes should you avoid? + +These are the traps that make the grader fail even when your NumPy is correct: + +- **Leaving the previous exercise's code in `app.py`.** Everything is written in that one file, and from exercise `015` onwards the test compares the entire console output with `==`. One leftover `print()` from exercise `012` and a perfectly correct answer fails. Delete or comment out what you no longer need. +- **Confusing printing with assigning.** Exercises `013` and `014` are graded by importing the variable (`from app import arr`), so computing the value inside a `print()` without storing it in `arr` fails. Exercise `015` wants both things: the variable *and* the printed mean. +- **Typing the expected result by hand.** Exercises `004`, `005`, `007`, `008`, `009`, `010`, `011` and `012` run a regex that rejects the literal answer in your source, so `print("[0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]")` or `print(80)` will never pass. +- **Counting from one.** The "fifth element" in exercise `007` is `arr[4]`. The expected output is `[0. 0. 0. 0. 1. 0. 0. 0. 0. 0.]`. +- **Reversing without the slice.** Exercise `009` requires the literal `::-1` in your code. `np.flip()` prints exactly the right vector and still fails the check. +- **Changing the import style.** The regex looks for `import numpy as np`. Neither `import numpy` nor `from numpy import *` passes exercises `002` and `003`. +- **Guessing the wrong size in `016` and `017`.** The instructions of `016` never say how big the matrix is — the `💻 Expected Output` block further down the same statement does: 5×5, ones on the border and a 3×3 block of zeros in the middle. In `017` you start from a 3×3 of ones and `np.pad()` turns it into a 5×5, printed right there too. Read that block before writing any code. +- **Unwrapping the result of `np.nonzero()` in `011`.** The expected output is the tuple `(array([0, 1, 4]),)`. Printing `np.nonzero(arr)[0]` gives `[0 1 4]` and fails. + +## ❓ Frequently asked questions + +### Do I need to know Python before learning NumPy? + +Yes, the basics. The tutorial is classified as intermediate because it assumes you already write variables, lists, `print()` and, most importantly, slices such as `lista[2:5]` or `lista[::-1]`. It assumes zero NumPy: the second exercise is the `import`. + +### Do all the exercises use the same file? + +Yes. You create `app.py` in exercise `001`, in the root of the project, and every following exercise is solved by editing that same file. That is what `incremental` grading means here, and it is also why cleaning up the previous answer matters before running the tests again. + +### Why does my exercise fail if the output looks correct? +Almost always for one of three reasons: there is an extra `print()` left over from a previous exercise and the test compares the full output with `==`; you wrote the expected result as a literal string and the anti-hardcoding regex caught it; or you solved it with a different function from the one the check looks for in the source, such as `np.flip()` instead of `[::-1]`. -## Contributors +### Which NumPy functions does the tutorial cover? -Thanks to these wonderful people ([emoji key](https://github.com/kentcdodds/all-contributors#emoji-key)): +Array creation with `array()`, `zeros()`, `ones()`, `eye()`, `arange()` and `random.random()`; shape and structure with `reshape()`, `pad()`, `diag()` and `nonzero()`; statistics with `max()` and `mean()`; the `itemsize` and `size` attributes; introspection with `__version__`, `show_config()` and `info()`; and index and slice notation applied to vectors and matrices. -1. [Alejandro Sanchez (alesanchezr)](https://github.com/alesanchezr), contribution: (coder) 💻, (idea) 🤔, (build-tests) ⚠️, (pull-request-review) 👀, (build-tutorial) ✅, (documentation) 📖 +### Do I have to install NumPy and pytest myself? -2. [Paolo (plucodev)](https://github.com/plucodev), contribution: (bug reports) 🐛, (coder) 💻, (translation) 🌎 +Only if you work on your own machine. The repository ships a dev container that, when the Codespace is created, installs Python 3.10, Node.js 22, `numpy==1.24.2`, `pandas`, `pytest==6.2.5` and LearnPack with its Python plugin. Locally it is two commands: a `pip3 install` for the Python packages and an `npm i` for LearnPack and its Python plugin. -3. [Ricardo Rodriguez (RickRodriguez8080)](https://github.com/RickRodriguez8080) contribution: (build-tutorial) ✅, (documentation) 📖 +### Are the solutions included, and does the tutorial cost anything? -This project follows the [all-contributors](https://github.com/kentcdodds/all-contributors) specifications. +19 of the 21 folders include a `solution.hide.py` file with the reference answer; LearnPack keeps it out of the way while you work, but it lives in the repository if you get truly stuck. Opening and following the tutorial costs nothing, and the code you write in `app.py` is yours. Note that the repository does not include a `LICENSE` file, so the teaching material itself is not published under an open source license. -Contributions of any kind are welcome! + + +## 📚 Related tutorials + +If you are heading towards data analysis, these interactive tutorials sit well around this one: + +- [Learn Python Interactively (beginner)](https://4geeks.com/en/interactive-exercise/python-beginner-exercises) — the previous step if variables and lists still feel new. +- [Learn Python Loops and lists Interactively](https://4geeks.com/en/interactive-exercise/python-loops-lists-exercises) — slicing practice, which is what this tutorial leans on hardest. +- [Linear Algebra in Python and NumPy](https://4geeks.com/en/interactive-exercise/linear-algebra-in-python-and-numpy) — the natural next step: dot products, determinants and eigenvalues with the same library. +- [Master Python by practice (interactive)](https://4geeks.com/en/interactive-exercise/master-python-exercises) — more general practice once you are done. + +## 🚀 How to start + +The fastest route needs no local installation at all: open the repository in [GitHub Codespaces](https://codespaces.new/?repo=4GeeksAcademy/numpy-tutorial-exercises) (recommended) or in [Gitpod](https://gitpod.io#https://github.com/4GeeksAcademy/numpy-tutorial-exercises.git). + +> 💡 Once VSCode opens, the LearnPack exercises should start on their own. If they do not, type `learnpack start` in the terminal. + +## 💻 Local installation + +1. Install [LearnPack](https://learnpack.co) and its Python plugin. You need Node.js 22 and Python 3.10 or higher: + + ```bash + npm i @learnpack/learnpack@5.0.348 -g && learnpack plugins:install @learnpack/python@1.0.3 + ``` + +2. Clone the repository and enter the folder: + + ```bash + git clone https://github.com/4GeeksAcademy/numpy-tutorial-exercises.git + cd numpy-tutorial-exercises + ``` + +3. Install the Python dependencies and start the tutorial from the same level as `learn.json`: + + ```bash + pip3 install pytest==6.2.5 mock pytest-testdox toml numpy==1.24.2 pandas + learnpack start + ``` + +## 📚 How the exercises are organized + +Every exercise lives in its own folder inside [`.learn/exercises`](https://github.com/4GeeksAcademy/numpy-tutorial-exercises/tree/HEAD/.learn/exercises) and contains only text and tests: + +- **`README.md`** — the statement in English, with the instructions, hints and, in several exercises, the exact expected output. +- **`README.es.md`** — the same statement in Spanish. +- **`test.py`** — the pytest script that grades the exercise. Reading it is the fastest way to understand exactly what is expected of you. +- **`solution.hide.py`** — the reference solution, present in 19 of the 21 folders (every one except `000-welcome` and `001-create-entry-file`). + +The file you actually edit, `app.py`, is not inside these folders: it lives in the root of the repository, next to [`learn.json`](https://github.com/4GeeksAcademy/numpy-tutorial-exercises/blob/HEAD/learn.json), and it is shared by every exercise. The `000-welcome` folder is the exception to everything: reading only, with no test and no solution. + +## 🤝 Contributors + +Thanks to these people, who built, tested and translated the exercises: [Alejandro Sánchez (alesanchezr)](https://github.com/alesanchezr), [Tomás Gonzáles (tommygonzaleza)](https://github.com/tommygonzaleza), [Paolo Lucano (plucodev)](https://github.com/plucodev) and [Marco Gómez (marcogonzalo)](https://github.com/marcogonzalo). + +This project follows the [all-contributors](https://github.com/kentcdodds/all-contributors) specification. All contributions are welcome: if you spot a bug or a typo, open an issue or a pull request in the [repository](https://github.com/4GeeksAcademy/numpy-tutorial-exercises/issues). + +This and many other exercises are built by students as part of the 4Geeks Academy [Coding Bootcamp](https://4geeksacademy.com/us/coding-bootcamp) by Alejandro Sánchez and many other contributors. Find out more about our [Full Stack Developer Course](https://4geeksacademy.com/us/coding-bootcamps/part-time-full-stack-developer) and our [Data Science and Machine Learning Bootcamp](https://4geeksacademy.com/us/coding-bootcamps/datascience-machine-learning). See the full list of people who have contributed code in the [contributors graph](https://github.com/4GeeksAcademy/numpy-tutorial-exercises/graphs/contributors). + + From 2071a36bdae8f188af0bda9a0f7fb4b2c1aba16e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nacho=20L=C3=B3pez?= <145539062+KrilinZ@users.noreply.github.com> Date: Mon, 3 Aug 2026 14:14:06 +0200 Subject: [PATCH 2/2] docs(readme): rewrite for clarity, SEO and AI answer engines --- README.es.md | 214 +++++++++++++++++++++++++++++++++++++++++++-------- 1 file changed, 180 insertions(+), 34 deletions(-) diff --git a/README.es.md b/README.es.md index e84538d..7e26b97 100644 --- a/README.es.md +++ b/README.es.md @@ -1,61 +1,207 @@ -# Welcome to Numpy exercise tutorial +
-Por @alesanchezr y otros contibuyentes en 4Geeks Academy. - +# Tutorial Interactivo de Numpy -NumPy (y Pandas) son las librerías #1 para Machine Learning, no hay manera que puedas realizar cualquier cosa sin ellas. +[![Certificado por 4Geeks](https://img.shields.io/badge/4Geeks-tutorial%20certificado-2563eb)](https://4geeks.com) +[![Autocorregido con LearnPack](https://img.shields.io/badge/LearnPack-autocorregido-2563eb)](https://learnpack.co) +[![Abrir en Codespaces](https://img.shields.io/badge/Abrir%20en-Codespaces-fb5a1f)](https://codespaces.new/?repo=4GeeksAcademy/numpy-tutorial-exercises) -Este tutorial interactivo te va a ayudar a familiarizarte con ello, a dominar las funcionalidades más usadas y a ayudarte a limpiar tu primer set de datos. +🇪🇸 [Leer en español](https://github.com/4GeeksAcademy/numpy-tutorial-exercises/blob/HEAD/README.es.md) · 🇬🇧 [Read in English](https://github.com/4GeeksAcademy/numpy-tutorial-exercises/blob/HEAD/README.md) -- Documentación de NumPy. -- Vectores. -- Matrices. -- Valores aleatorios, Media. +![Portada del tutorial interactivo de NumPy, con el texto Learn Python Numpy interactive junto al logo del cubo de NumPy en azul y azul claro sobre fondo negro](https://raw.githubusercontent.com/4GeeksAcademy/numpy-tutorial-exercises/master/.learn/assets/preview.jpeg) -> Nota: Todo el tutorial es completamente 👆 interactivo, ✅ con corrección automática y 📹 videos tutoriales. +
+ -Estos ejercicios fueron construidos en colaboración. ¡Te necesitamos! Si consigues algún error o falta de ortografía, por favor ayúdanos y repórtalos. +Este tutorial de LearnPack enseña NumPy con 21 ejercicios: una página de bienvenida y 20 retos autocorregidos sobre creación de arrays, indexado, slicing, cambio de forma y estadística básica. Todo se escribe en un único fichero `app.py` y lo corrigen 53 comprobaciones de pytest. Practicas `zeros`, `ones`, `arange`, `reshape`, `eye`, `pad`, `diag`, `nonzero`, `random`, `max` y `mean`. Duración estimada: 10 horas, nivel intermedio. -## Instalación en un clic (recomendado) -Puedes empezar estos ejercicios en pocos segundos haciendo clic en: [Abrir en Codespaces](https://codespaces.new/?repo=4GeeksAcademy/numpy-tutorial-exercises) (recomendado) o [Abrir en Gitpod](https://gitpod.io#https://github.com/4GeeksAcademy/numpy-tutorial-exercises.git). +## 📋 Ficha del tutorial -> Una vez ya tengas abierto VSCode, los ejercicios de LearnPack deberían empezar automáticamente; si esto no sucede puedes intentar empezar los ejercicios escribiendo este comando en tu terminal: `$ learnpack start` +- **Dificultad:** intermedia +- **Duración estimada:** 10 horas +- **Lenguaje:** Python 3 +- **Tecnologías:** Python, NumPy 1.24.2, pytest, LearnPack +- **Ejercicios:** 21 carpetas — 1 de bienvenida + 20 con corrección automática +- **Corrección:** modo `incremental`, con LearnPack y pytest (53 comprobaciones `@pytest.mark.it`) +- **Idiomas:** español (`README.es.md`) e inglés (`README.md`) dentro de cada ejercicio + -## Instalación local +## 🎯 ¿Qué vas a aprender? -1. Clona o descarga este repositorio. +NumPy es la librería de arrays sobre la que están construidos Pandas, scikit-learn y casi todo el Python científico. Este tutorial no te explica la teoría de los espacios vectoriales: te hace teclear la API hasta que se te queda. Cada ejercicio son una o dos líneas de código, así que en una sola sesión tocas las funciones que vas a usar todos los días. -2. Asegúrate de tener [LearnPack](https://learnpack.co) instalado, una versión de node.js 14 o superior y una versión de Python 3 o superior. Este es el comando para instalar LearnPack: +Al terminar vas a manejar con soltura: -```bash -$ npm i @learnpack/learnpack -g && learnpack plugins:install @learnpack/python -``` +- El import canónico, `import numpy as np`, y cómo mirar la instalación con `np.__version__` y `np.show_config()`. +- Cómo consultar la documentación sin salir de Python, con `np.info(np.add)`. +- La creación de arrays desde cero: `np.zeros()`, `np.ones()`, `np.eye()`, `np.arange()` y `np.array()`. +- El cálculo de lo que ocupa un array en memoria multiplicando `.itemsize` por `.size` (un vector de 10 decimales ocupa 80 bytes). +- La modificación de valores por posición y por rebanada: `arr[4] = 1`, `matrix[1:-1, 1:-1] = 0`, `arr[::-1]`, `matrix[1::2, ::2] = 1`. +- El cambio de forma con `reshape()`, para convertir un vector de 9 elementos en una matriz de 3×3. +- La búsqueda dentro de un array con `np.nonzero()` y cómo leer la tupla de índices que devuelve. +- La generación de datos aleatorios con `np.random.random()` y su resumen con `.max()` y `.mean()`. +- El crecimiento de una matriz con `np.pad()` y la extracción de su diagonal con `np.diag()`. +- Los casos raros que sorprenden a todo el mundo: `np.nan == np.nan` es `False`, `np.nan in set([np.nan])` es `True` y `0.3 == 3 * 0.1` es `False`. + +Los ejercicios son así de cortos. Estas son las rebanadas con las que se construye el último, un tablero de ajedrez de 8×8: + +```python +import numpy as np + +matrix = np.zeros((6, 6)) -3. Empieza el tutorial/ejercicios corriendo estos comandos en el mismo nivel donde se encuentra tu archivo learn.json: +matrix[::2, 1::2] = 1 # unos en las filas pares, columnas impares -```bash -$ pip3 install pytest==6.2.5 mock pytest-testdox toml numpy==1.24.2 pandas -$ learnpack start +print(matrix[0]) # [0. 1. 0. 1. 0. 1.] ``` -> Nota: Estos ejercicios tienen calificación automática. Los tests son muy rígidos y estrictos, mi recomendación es que no prestes demasiada atención a los tests y los uses solo como una sugerencia o podrías frustrarte. +## 👀 ¿Qué vas a construir? - +Aquí no hay proyecto final. Construyes un solo fichero, `app.py`, que creas en el primer ejercicio y reescribes en cada paso siguiente. Estas son las 21 carpetas de `.learn/exercises`, en orden: + +1. **`000` Welcome** — solo lectura y sin test: qué es NumPy, para qué se usa y enlaces a la documentación oficial y a un vídeo. +2. **`001` Create Entry File** — crear `app.py` en la raíz del proyecto. El único test comprueba que el fichero existe. +3. **`002` Import NumPy** — importar la librería con el alias `np`. +4. **`003` NumPy Version** — imprimir la versión instalada usando `np.__version__`. +5. **`004` Your First Vector** — imprimir un vector nulo de tamaño 10 creado con `np.zeros()`. +6. **`005` Array Memory Size** — imprimir `80`, la memoria que ocupa ese vector, a partir de `.itemsize` y `.size`. +7. **`006` NumPy Documentation** — imprimir la documentación de `np.add()` con `np.info()`. +8. **`007` Change Vector Values** — un vector nulo de tamaño 10 cuyo quinto elemento (índice `4`) vale `1`. +9. **`008` Vector Ranging Values** — un vector con todos los enteros del 10 al 49, creado con `np.arange()`. +10. **`009` Reverse Vector** — los enteros del 0 al 9 impresos al revés usando `array[::-1]`. +11. **`010` Matrix with Ranging Values** — los números del 0 al 8 convertidos en una matriz de 3×3 con `reshape()`. +12. **`011` Find Indexes of Non Zero Elements** — `np.nonzero()` sobre `[1,2,0,0,4,0]`, imprimiendo `(array([0, 1, 4]),)`. +13. **`012` Identity Matrix** — una matriz identidad de 3×3 creada con `np.eye()`. +14. **`013` Random Values Array** — una variable llamada `arr` con un array de 3 valores aleatorios. +15. **`014` Minimum and Maximum** — `arr` con 10 valores aleatorios, imprimiendo el mayor con `.max()`. +16. **`015` Mean Value** — `arr` con 10 valores aleatorios, imprimiendo su media con `.mean()`. +17. **`016` Array Border** — una matriz de 5×5 de unos con el centro puesto a cero mediante `matrix[1:-1, 1:-1]`. +18. **`017` Add Border to Array** — una matriz de 3×3 de unos rodeada por un borde de ceros con `np.pad()`. +19. **`018` Result of Expressions** — imprimir los seis resultados de las comparaciones con `nan` e `inf`: `nan`, `False`, `False`, `nan`, `True`, `False`. +20. **`019` Diagonal** — imprimir `[0 4 8]`, la diagonal de una matriz de 3×3, usando `np.diag()`. +21. **`020` Checkerboard Pattern** — una matriz de 8×8 rellena con un patrón de tablero de ajedrez de ceros y unos. + +## 🎓 ¿Qué necesitas antes de empezar? + +El tutorial está catalogado como **intermedio**, y el motivo es Python, no las matemáticas: aquí no hay nada más allá de la aritmética, las «matrices» son rejillas de números. Lo que sí necesitas es: + +- **Python básico bien asentado** — variables, `print()`, listas y sobre todo la notación de rebanadas. La mitad de los ejercicios se resuelven con un slice del tipo `[::-1]`, `[1:-1, 1:-1]` o `[1::2, ::2]`. +- **Cero experiencia previa con NumPy.** El ejercicio `002` empieza por el `import numpy as np` y cada función llega con una pista y un enlace a su página en numpy.org. +- **Un entorno de Python 3 con NumPy y pytest.** Si abres el repositorio en Codespaces, el dev container instala por ti Python 3.10, `numpy==1.24.2` y `pytest==6.2.5`. En local los instalas tú. +- **Node.js 22**, únicamente si vas a correr los ejercicios en tu propia máquina, porque LearnPack es una herramienta de línea de comandos de Node. + +## ✅ ¿Cómo funciona la corrección automática? + +20 de las 21 carpetas traen un fichero `test.py` y entre todas suman 53 comprobaciones escritas con `@pytest.mark.it("...")`, así que cada fallo te dice en una frase qué se esperaba. El modo de corrección es `incremental`: los ejercicios se apoyan unos en otros y todos leen el mismo `app.py` que vive en la raíz del repositorio, no dentro de la carpeta del ejercicio. + +Hay cuatro tipos de comprobación, y saber cuál tienes delante te ahorra mucho tiempo: + +- **Comprobaciones de salida:** capturan lo que imprime tu programa con el fixture `capsys` de pytest. Hasta el ejercicio `012` solo exigen que el texto esperado aparezca en algún punto de tu salida, pero del `015` al `020` comparan la consola entera con `==`, carácter a carácter. +- **Comprobaciones del código fuente:** abren `app.py` y buscan la función que se te pidió usar: `zeros(`, `ones(`, `arange(`, `reshape(`, `eye(`, `pad(`, `diag(`, `nonzero`, `array`, `random(`, `max(`, `mean(`, `info(`, `itemsize`, `size`. +- **Comprobaciones anti-copia:** lanzan una expresión regular que falla si el resultado esperado está escrito tal cual en tu fichero. Ocho ejercicios llevan una. +- **Comprobaciones de importación:** en `013`, `014` y `015` ejecutan `from app import arr`, así que `arr` tiene que existir como variable en el nivel superior del módulo. + +Lanza los tests desde la interfaz de LearnPack después de editar `app.py` y lee la descripción de la comprobación que falla antes de tocar nada. + +## 💡 ¿Qué errores debes evitar? + +Estas son las trampas que hacen fallar la corrección aunque tu NumPy sea correcto: + +- **Dejar en `app.py` el código del ejercicio anterior.** Todo se escribe en ese mismo fichero y, a partir del `015`, el test compara la salida completa de la consola con `==`. Un `print()` olvidado del ejercicio `012` tumba una respuesta perfectamente válida. Borra o comenta lo que ya no necesites. +- **Confundir imprimir con asignar.** Los ejercicios `013` y `014` se corrigen importando la variable (`from app import arr`), así que calcular el valor dentro de un `print()` sin guardarlo en `arr` falla. El `015` quiere las dos cosas: la variable *y* la media impresa. +- **Escribir el resultado esperado a mano.** Los ejercicios `004`, `005`, `007`, `008`, `009`, `010`, `011` y `012` llevan una regex que rechaza la respuesta literal en tu código: `print("[0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]")` o `print(80)` no van a pasar nunca. +- **Contar desde uno.** El «quinto elemento» del ejercicio `007` es `arr[4]`. La salida esperada es `[0. 0. 0. 0. 1. 0. 0. 0. 0. 0.]`. +- **Invertir el vector sin la rebanada.** El ejercicio `009` exige el literal `::-1` en tu código. `np.flip()` imprime exactamente el vector correcto y aun así falla la comprobación. +- **Cambiar la forma del import.** La regex busca `import numpy as np`. Ni `import numpy` ni `from numpy import *` superan los ejercicios `002` y `003`. +- **Equivocarte de tamaño en el `016` y el `017`.** Las instrucciones del `016` no dicen de qué tamaño es la matriz, pero el bloque `💻 Expected Output` que viene justo debajo en el mismo enunciado sí: 5×5, con unos en el borde y un bloque de 3×3 de ceros en el centro. En el `017` partes de una de 3×3 de unos y `np.pad()` la convierte en una de 5×5, también impresa ahí. Lee ese bloque antes de escribir nada. +- **Desenvolver el resultado de `np.nonzero()` en el `011`.** La salida esperada es la tupla `(array([0, 1, 4]),)`. Imprimir `np.nonzero(arr)[0]` da `[0 1 4]` y falla. + +## ❓ Preguntas frecuentes + +### ¿Hace falta saber Python antes de aprender NumPy? + +Sí, lo básico. El tutorial está clasificado como intermedio porque da por sabidas las variables, las listas, el `print()` y, sobre todo, las rebanadas del tipo `lista[2:5]` o `lista[::-1]`. De NumPy no da nada por sabido: el segundo ejercicio es precisamente el `import`. + +### ¿Todos los ejercicios usan el mismo fichero? + +Sí. Creas `app.py` en el ejercicio `001`, en la raíz del proyecto, y todos los ejercicios siguientes se resuelven editando ese mismo fichero. Eso es lo que significa aquí la corrección `incremental`, y también por eso conviene limpiar la respuesta anterior antes de volver a lanzar los tests. + +### ¿Por qué falla mi ejercicio si la salida se ve bien? -## Colaboradores - -Gracias a estas personas maravillosas ([emoji key](https://github.com/kentcdodds/all-contributors#emoji-key)): +Casi siempre por una de tres razones: te queda un `print()` suelto de un ejercicio anterior y el test compara la salida completa con `==`; escribiste el resultado esperado como texto literal y lo cazó la regex anti-copia; o lo resolviste con una función distinta a la que la comprobación busca en el código, como `np.flip()` en lugar de `[::-1]`. -1. [Alejandro Sanchez (alesanchezr)](https://github.com/alesanchezr), contribución: (programador) 💻, (idea) 🤔, (build-tests) ⚠️, (pull-request-review) 👀, (build-tutorial) ✅, (documentación) 📖 +### ¿Qué funciones de NumPy cubre el tutorial? -2. [Paolo (plucodev)](https://github.com/plucodev), contribución: (bug reports) 🐛, (programador) 💻, (traducción) 🌎 +Creación de arrays con `array()`, `zeros()`, `ones()`, `eye()`, `arange()` y `random.random()`; forma y estructura con `reshape()`, `pad()`, `diag()` y `nonzero()`; estadística con `max()` y `mean()`; los atributos `itemsize` y `size`; introspección con `__version__`, `show_config()` e `info()`; y la notación de índices y rebanadas aplicada a vectores y matrices. -3. [Marco Gómez (marcogonzalo)](https://github.com/marcogonzalo), contribution: (bug reports) 🐛, (traducción) 🌎 +### ¿Tengo que instalar NumPy y pytest por mi cuenta? -Este proyecto sigue la especificación [all-contributors](https://github.com/kentcdodds/all-contributors). +Solo si trabajas en tu propia máquina. El repositorio incluye un dev container que, al crear el Codespace, instala Python 3.10, Node.js 22, `numpy==1.24.2`, `pandas`, `pytest==6.2.5` y LearnPack con su plugin de Python. En local son dos comandos: un `pip3 install` con los paquetes de Python y un `npm i` para LearnPack y su plugin de Python. -¡Todas las contribuciones son bienvenidas! +### ¿Vienen las soluciones y cuesta algo el tutorial? + +19 de las 21 carpetas incluyen un fichero `solution.hide.py` con la solución de referencia; LearnPack lo mantiene apartado mientras trabajas, pero está en el repositorio por si te atascas de verdad. Abrir y seguir el tutorial no cuesta nada y el código que escribas en `app.py` es tuyo. Eso sí, el repositorio no incluye fichero `LICENSE`, así que el material didáctico no está publicado bajo una licencia de código abierto. + + + +## 📚 Tutoriales relacionados + +Si vas camino del análisis de datos, estos tutoriales interactivos encajan bien alrededor de este: + +- [Aprende Python Interactivamente (Principiante)](https://4geeks.com/es/interactive-exercise/python-beginner-exercises-es) — el paso anterior si las variables y las listas todavía se te resisten. +- [Aprende listas y bucles de Python Interactivamente](https://4geeks.com/es/interactive-exercise/python-loops-lists-exercises-es) — práctica de rebanadas, que es justo donde más se apoya este tutorial. +- [Aprende las funciones de Python Interactivamente](https://4geeks.com/es/interactive-exercise/python-function-exercises-es) — para dejar de escribir todo suelto en un fichero. +- [Domina Python Practicando (interactivo)](https://4geeks.com/es/interactive-exercise/master-python-exercises-es) — más práctica general cuando termines. + +## 🚀 Cómo empezar + +La vía rápida no necesita ninguna instalación local: abre el repositorio en [GitHub Codespaces](https://codespaces.new/?repo=4GeeksAcademy/numpy-tutorial-exercises) (recomendado) o en [Gitpod](https://gitpod.io#https://github.com/4GeeksAcademy/numpy-tutorial-exercises.git). + +> 💡 Cuando se abra VSCode, los ejercicios de LearnPack deberían arrancar solos. Si no lo hacen, escribe `learnpack start` en la terminal. + +## 💻 Instalación local + +1. Instala [LearnPack](https://learnpack.co) y su plugin de Python. Necesitas Node.js 22 y Python 3.10 o superior: + + ```bash + npm i @learnpack/learnpack@5.0.348 -g && learnpack plugins:install @learnpack/python@1.0.3 + ``` + +2. Clona el repositorio y entra en la carpeta: + + ```bash + git clone https://github.com/4GeeksAcademy/numpy-tutorial-exercises.git + cd numpy-tutorial-exercises + ``` + +3. Instala las dependencias de Python y arranca el tutorial al mismo nivel que `learn.json`: + + ```bash + pip3 install pytest==6.2.5 mock pytest-testdox toml numpy==1.24.2 pandas + learnpack start + ``` + +## 📚 Cómo están organizados los ejercicios + +Cada ejercicio vive en su propia carpeta dentro de [`.learn/exercises`](https://github.com/4GeeksAcademy/numpy-tutorial-exercises/tree/HEAD/.learn/exercises) y contiene solo texto y tests: + +- **`README.es.md`** — el enunciado en español, con las instrucciones, las pistas y, en varios ejercicios, la salida exacta que se espera. +- **`README.md`** — el mismo enunciado en inglés. +- **`test.py`** — el script de pytest que corrige el ejercicio. Leerlo es la forma más rápida de entender qué se espera exactamente de ti. +- **`solution.hide.py`** — la solución de referencia, presente en 19 de las 21 carpetas (todas menos `000-welcome` y `001-create-entry-file`). + +El fichero que de verdad editas, `app.py`, no está en esas carpetas: vive en la raíz del repositorio, junto a [`learn.json`](https://github.com/4GeeksAcademy/numpy-tutorial-exercises/blob/HEAD/learn.json), y lo comparten todos los ejercicios. La carpeta `000-welcome` es la excepción a todo: es solo de lectura, sin test y sin solución. + +## 🤝 Colaboradores + +Gracias a estas personas, que construyeron, probaron y tradujeron los ejercicios: [Alejandro Sánchez (alesanchezr)](https://github.com/alesanchezr), [Tomás Gonzáles (tommygonzaleza)](https://github.com/tommygonzaleza), [Paolo Lucano (plucodev)](https://github.com/plucodev) y [Marco Gómez (marcogonzalo)](https://github.com/marcogonzalo). + +Este proyecto sigue la especificación [all-contributors](https://github.com/kentcdodds/all-contributors). Todas las contribuciones son bienvenidas: si encuentras un fallo o una errata, abre una issue o una pull request en el [repositorio](https://github.com/4GeeksAcademy/numpy-tutorial-exercises/issues). + +Este y otros ejercicios son usados para [aprender a programar](https://4geeksacademy.com/es/aprender-a-programar/aprender-a-programar-desde-cero) por los alumnos de 4Geeks Academy [Coding Bootcamp](https://4geeksacademy.com/us/coding-bootcamp), realizado por Alejandro Sánchez y muchos otros colaboradores. Conoce más sobre nuestros [cursos de programación](https://4geeksacademy.com/es/curso-de-programacion-desde-cero) para convertirte en [Full Stack Developer](https://4geeksacademy.com/es/coding-bootcamps/desarrollador-full-stack), o nuestro [Bootcamp de Data Science y Machine Learning](https://4geeksacademy.com/es/coding-bootcamps/curso-datascience-machine-learning). Puedes ver a todas las personas que han aportado código en el [gráfico de contribuidores](https://github.com/4GeeksAcademy/numpy-tutorial-exercises/graphs/contributors). + +