├── .devcontainer └── devcontainer.json ├── .github └── workflows │ └── learnpack-audit.yml ├── .gitignore ├── .gitpod.Dockerfile ├── .gitpod.yml ├── .vscode └── settings.json ├── CHANGELOG.md ├── LICENSE.md ├── README.es.md ├── README.md ├── badge-master-python.png ├── exercises ├── 000-welcome │ ├── README.es.md │ └── README.md ├── 001-hello_world │ ├── README.es.md │ ├── README.md │ ├── app.py │ ├── solution.hide.py │ └── test.py ├── 002-sum_of_three_numbers │ ├── README.es.md │ ├── README.md │ ├── app.py │ ├── solution.hide.py │ └── test.py ├── 003-area_of_right_triangle │ ├── README.es.md │ ├── README.md │ ├── app.py │ ├── solution.hide.py │ └── test.py ├── 004-hello_harry │ ├── README.es.md │ ├── README.md │ ├── app.py │ ├── solution.hide.py │ └── test.py ├── 005-previous_and_next │ ├── README.es.md │ ├── README.md │ ├── app.py │ ├── solution.hide.py │ └── test.py ├── 006-apple_sharing │ ├── README.es.md │ ├── README.md │ ├── app.py │ ├── solution.hide.py │ └── test.py ├── 006.1-square_value_of_number │ ├── README.es.md │ ├── README.md │ ├── app.py │ ├── solution.hide.py │ └── test.py ├── 007-hours_and_minutes │ ├── README.es.md │ ├── README.md │ ├── app.py │ ├── solution.hide.py │ └── test.py ├── 008-two_timestamps │ ├── README.es.md │ ├── README.md │ ├── app.py │ ├── solution.hide.py │ └── test.py ├── 009-two_digits │ ├── README.es.md │ ├── README.md │ ├── app.py │ ├── solution.hide.py │ └── test.py ├── 010-swap_digits │ ├── README.es.md │ ├── README.md │ ├── app.py │ ├── solution.hide.py │ └── test.py ├── 011-last_two_digits │ ├── README.es.md │ ├── README.md │ ├── app.py │ ├── solution.hide.py │ └── test.py ├── 012-tens_digit │ ├── README.es.md │ ├── README.md │ ├── app.py │ ├── solution.hide.py │ └── test.py ├── 013-sum_of_digits │ ├── README.es.md │ ├── README.md │ ├── app.py │ ├── solution.hide.py │ └── test.py ├── 014-digit_after_decimal_point │ ├── README.es.md │ ├── README.md │ ├── app.py │ ├── solution.hide.py │ └── test.py ├── 015-car_route │ ├── README.es.md │ ├── README.md │ ├── app.py │ ├── solution.hide.py │ └── test.py ├── 016-century │ ├── README.es.md │ ├── README.md │ ├── app.py │ ├── solution.hide.py │ └── test.py ├── 017-total_cost │ ├── README.es.md │ ├── README.md │ ├── app.py │ ├── solution.hide.py │ └── test.py ├── 018-day_of_week │ ├── README.es.md │ ├── README.md │ ├── app.py │ ├── solution.hide.py │ └── test.py ├── 019-digital_clock │ ├── README.es.md │ ├── README.md │ ├── app.py │ ├── solution.hide.py │ └── test.py ├── 020-factorial │ ├── README.es.md │ ├── README.md │ ├── app.py │ ├── solution.hide.py │ └── test.py ├── 021-square_root │ ├── README.es.md │ ├── README.md │ ├── app.py │ ├── solution.hide.py │ └── test.py ├── 022-Integral │ ├── README.es.md │ ├── README.md │ ├── app.py │ ├── solution.hide.py │ └── test.py ├── 023-list-and-tuple │ ├── README.es.md │ ├── README.md │ ├── app.py │ ├── solution.hide.py │ └── test.py ├── 024-class-with-two-methods │ ├── README.es.md │ ├── README.md │ ├── app.py │ ├── solution.hide.py │ └── test.py ├── 025-print-formula │ ├── README.es.md │ ├── README.md │ ├── app.py │ ├── solution.hide.py │ └── test.py ├── 026-two-dimensional-array │ ├── README.es.md │ ├── README.md │ ├── app.py │ ├── solution.hide.py │ └── test.py ├── 027-sequence-of-words │ ├── README.es.md │ ├── README.md │ ├── app.py │ ├── solution.hide.py │ └── test.py ├── 028-sequence-of-lines │ ├── README.es.md │ ├── README.md │ ├── app.py │ ├── solution.hide.py │ └── test.py ├── 029-remove-duplicate-words │ ├── README.es.md │ ├── README.md │ ├── app.py │ ├── solution.hide.py │ └── test.py ├── 030-divisable-binary │ ├── README.es.md │ ├── README.md │ ├── app.py │ ├── solution.hide.py │ └── test.py ├── 031-sum-eigth-digit │ ├── README.es.md │ ├── README.md │ ├── app.py │ └── solution.hide.py ├── 032-numbers-of-letters-and-digits │ ├── README.es.md │ ├── README.md │ ├── app.py │ ├── solution.hide.py │ └── test.py ├── 033-number-of-uppercase │ ├── README.es.md │ ├── README.md │ ├── app.py │ └── solution.hide.py ├── 034-a_aa_aaa_aaaa │ ├── README.es.md │ ├── README.md │ ├── app.py │ ├── solution.hide.py │ └── test.py ├── 035-square-each-odd-number │ ├── README.es.md │ ├── README.md │ ├── app.py │ └── solution.hide.py ├── 036-net-amount │ ├── README.es.md │ ├── README.md │ ├── app.py │ ├── solution.hide.py │ └── test.py ├── 037-validity-of-password │ ├── README.es.md │ ├── README.md │ ├── app.py │ ├── solution.hide.py │ └── test.py ├── 038-sort-tuples-ascending │ ├── README.es.md │ ├── README.md │ ├── app.py │ ├── solution.hide.py │ └── test.py ├── 039-class-that-iterates │ ├── README.es.md │ ├── README.md │ ├── app.py │ └── solution.hide.py ├── 040-compute-robot-distance │ ├── README.es.md │ ├── README.md │ ├── app.py │ ├── solution.hide.py │ └── test.py ├── 041-frequency-of-words │ ├── README.es.md │ ├── README.md │ ├── app.py │ ├── solution.hide.py │ └── test.py ├── 042-understanding_classes │ ├── README.es.md │ ├── README.md │ ├── app.py │ ├── solution.hide.py │ └── test.py ├── 042.1-init_and_str_methods │ ├── README.es.md │ ├── README.md │ ├── app.py │ ├── solution.hide.py │ └── test.py ├── 043-inheritance_and_polymorphism │ ├── README.es.md │ ├── README.md │ ├── app.py │ ├── solution.hide.py │ └── test.py ├── 044-static_methods │ ├── README.es.md │ ├── README.md │ ├── app.py │ ├── solution.hide.py │ └── test.py └── 045-class_methods │ ├── README.es.md │ ├── README.md │ ├── app.py │ ├── solution.hide.py │ └── test.py ├── learn.json └── preview.gif /.devcontainer/devcontainer.json: -------------------------------------------------------------------------------- 1 | 2 | // For format details, see https://aka.ms/devcontainer.json. For config options, see the 3 | // README at: https://github.com/devcontainers/templates/tree/main/src/python 4 | { 5 | "name": "Python 3", 6 | // Or use a Dockerfile or Docker Compose file. More info: https://containers.dev/guide/dockerfile 7 | "image": "mcr.microsoft.com/devcontainers/python:0-3.10", 8 | "features": { 9 | "ghcr.io/devcontainers/features/node:1": { 10 | "nodeGypDependencies": true, 11 | "version": "16" 12 | } 13 | }, 14 | "customizations": { 15 | "vscode": { 16 | "settings": { 17 | "editor.defaultFormatter": "esbenp.prettier-vscode", 18 | "workbench.editorAssociations": { 19 | "*.md": "vscode.markdown.preview.editor" 20 | } 21 | }, 22 | "extensions": ["learn-pack.learnpack-vscode"] 23 | } 24 | }, 25 | "onCreateCommand": "pip3 install pytest==6.2.5 pytest-testdox mock && npm i @learnpack/learnpack@5.0.19 -g && learnpack plugins:install @learnpack/python@1.0.6" 26 | 27 | // Features to add to the dev container. More info: https://containers.dev/features. 28 | // "features": {}, 29 | 30 | // Use 'forwardPorts' to make a list of ports inside the container available locally. 31 | // "forwardPorts": [], 32 | 33 | // Use 'postCreateCommand' to run commands after the container is created. 34 | // "postCreateCommand": "pip3 install --user -r requirements.txt", 35 | 36 | // Uncomment to connect as root instead. More info: https://aka.ms/dev-containers-non-root. 37 | // "remoteUser": "root" 38 | } 39 | 40 | -------------------------------------------------------------------------------- /.github/workflows/learnpack-audit.yml: -------------------------------------------------------------------------------- 1 | # This workflow will do a clean install of node dependencies, cache/restore them, build the source code and run tests across different versions of node 2 | # For more information see: https://help.github.com/actions/language-and-framework-guides/using-nodejs-with-github-actions 3 | 4 | name: Learnpack audit 5 | 6 | on: 7 | push: 8 | branches: [ main ] 9 | pull_request: 10 | branches: [ main ] 11 | 12 | jobs: 13 | build: 14 | 15 | runs-on: ubuntu-latest 16 | 17 | strategy: 18 | matrix: 19 | node-version: [20.x] 20 | # See supported Node.js release schedule at https://nodejs.org/en/about/releases/ 21 | 22 | steps: 23 | - uses: actions/checkout@v2 24 | - name: Use Node.js ${{ matrix.node-version }} 25 | uses: actions/setup-node@v2 26 | with: 27 | node-version: ${{ matrix.node-version }} 28 | - run: npm install @learnpack/learnpack@latest -g 29 | - run: learnpack audit -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Ignore everything 2 | /* 3 | 4 | !.gitignore 5 | !.gitpod.yml 6 | !.devcontainer 7 | !.devcontainer/* 8 | !.gitpod.Dockerfile 9 | !bc.json 10 | !learn.json 11 | !README.md 12 | !README.es.md 13 | !.vscode 14 | 15 | !/exercises 16 | !/exercises/* 17 | 18 | *.pyc 19 | __pycache__/ 20 | .pytest_cache/ 21 | 22 | !/.learn 23 | /.learn/** 24 | !/.learn/resets 25 | !/.learn/resets/** 26 | -------------------------------------------------------------------------------- /.gitpod.Dockerfile: -------------------------------------------------------------------------------- 1 | FROM gitpod/workspace-full:latest 2 | 3 | SHELL ["/bin/bash", "-c"] 4 | 5 | RUN sudo apt-get update \ 6 | && sudo apt-get update \ 7 | && sudo apt-get clean \ 8 | && sudo rm -rf /var/cache/apt/* /var/lib/apt/lists/* /tmp/* 9 | 10 | # That Gitpod install pyenv for me? no, thanks 11 | WORKDIR /home/gitpod/ 12 | RUN rm .pyenv -Rf 13 | RUN rm .gp_pyenv.d -Rf 14 | RUN curl https://pyenv.run | bash 15 | 16 | 17 | RUN pyenv update && pyenv install 3.10.7 && pyenv global 3.10.7 18 | RUN pip install pipenv 19 | 20 | # remove PIP_USER environment 21 | USER gitpod 22 | RUN if ! grep -q "export PIP_USER=no" "$HOME/.bashrc"; then printf '%s\n' "export PIP_USER=no" >> "$HOME/.bashrc"; fi 23 | RUN echo "" >> $HOME/.bashrc 24 | RUN echo "unset DATABASE_URL" >> $HOME/.bashrc 25 | RUN echo "export DATABASE_URL" >> $HOME/.bashrc 26 | 27 | RUN pip3 install pytest==6.2.5 pytest-testdox mock 28 | RUN npm i @learnpack/learnpack@2.1.39 -g && learnpack plugins:install @learnpack/python@1.0.3 29 | -------------------------------------------------------------------------------- /.gitpod.yml: -------------------------------------------------------------------------------- 1 | image: 2 | file: .gitpod.Dockerfile 3 | 4 | ports: 5 | - port: 3000 6 | onOpen: ignore 7 | 8 | vscode: 9 | extensions: 10 | - learn-pack.learnpack-vscode 11 | 12 | github: 13 | prebuilds: 14 | # enable for the master/default branch (defaults to true) 15 | master: true 16 | # enable for pull requests coming from this repo (defaults to true) 17 | pullRequests: false 18 | # add a "Review in Gitpod" button as a comment to pull requests (defaults to true) 19 | addComment: false 20 | -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "files.autoSave": "afterDelay", 3 | "files.autoSaveDelay": 700, 4 | "editor.minimap.enabled": false, 5 | "workbench.editorAssociations": { 6 | "*.md": "vscode.markdown.preview.editor" 7 | } 8 | } -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Sep 16 2 | 3 | Niza Vera will be adding 13 exercises from [this Mastering Python Lesson in Repl.it](https://repl.it/classroom/invite/avFe7Od) 4 | 5 | ```bash 6 | 9.1. Sets: Number of distinct 7 | 9.2. Sets: Number of common 8 | 9.3. Sets: Intersection 9 | 9.4. Sets: Seen before 10 | 9.5. Sets: Guess the number 11 | A.1. Dicts: Number of occurrences 12 | A.2. Dicts: Synonyms 13 | A.3. Dicts: Elections 14 | A.4. Dicts: Most frequent word 15 | A.5. Dicts: Access rights 16 | A.6. Dicts: Countries and cities 17 | A.7. Dicts: Frequency analysis 18 | A.8. Dicts: English-Latin dictionary 19 | ``` 20 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | # TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 2 | 3 | By accessing Breathe Code we assume you accept these terms and conditions. Do not continue to use Breathe Code's content, applications or tutorials if you do not agree to take all of the terms and conditions stated on this page. 4 | 5 | Unless otherwise stated, Breathe Code and/or its licensors own the intellectual property rights for all material on Breathe Code. All intellectual property rights are reserved. You may access this from Breathe Code for your own personal use subjected to restrictions set in these terms and conditions. 6 | 7 | You must not: 8 | 9 | * Republish material from Breathe Code 10 | * Sell, rent or sub-license material from Breathe Code 11 | * Reproduce, duplicate or copy material from Breathe Code 12 | * Redistribute content from Breathe Code 13 | 14 | You can read the full version of Breathe Code's terms and conditions here: [Terms and Conditions](http://breatheco.de/terms-and-conditions) 15 | -------------------------------------------------------------------------------- /README.es.md: -------------------------------------------------------------------------------- 1 | 2 | # 🐍 Tutorial Master Python 3 | 4 | Por [@alesanchezr](https://twitter.com/alesanchezr) y [otros colaboradores](https://github.com/4GeeksAcademy//master-python-programming-exercises/graphs/contributors) de [4Geeks Academy](http://4geeksacademy.co/) 5 | 6 | 7 | 8 | 9 | 10 | Después de terminar la serie de principiantes, funciones y bucles; esta serie te preparará para tu próximo trabajo o cualquier otro desafío de programación. Practica todo lo necesario para construir algoritmos con Python, desde desafíos intermedios hasta difíciles. 11 | 12 | Todo el tutorial es 👆 interactivo y ✅ calificado automáticamente. 13 | 14 | Estos Ejercicios son colaborativos, ¡te necesitamos! Si encuentras algún error o falta de ortografía, por favor contribuye y repórtalo. 15 | 16 | 17 | 18 | ## Instalación en un clic (recomendado) 19 | 20 | Puedes empezar estos ejercicios en pocos segundos haciendo clic en: [Abrir en Codespaces](https://codespaces.new/?repo=4GeeksAcademy/master-python-programming-exercises) (recomendado) o [Abrir en Gitpod](https://gitpod.io#https://github.com/4GeeksAcademy/master-python-programming-exercises.git). 21 | 22 | > 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` 23 | 24 | ## Instalación local: 25 | 26 | 1. Asegúrate de instalar [LearnPack](https://learnpack.co), node.js version 14+ y Python version 3+. Este es el comando para instalar LearnPack: 27 | 28 | ```bash 29 | npm i @learnpack/learnpack@2.1.20 -g && learnpack plugins:install @learnpack/python@1.0.0 30 | ``` 31 | 32 | 2. Clona o descarga este repositorio en tu ambiente local. 33 | 34 | ```bash 35 | $ git clone https://github.com/4GeeksAcademy/master-python-programming-exercises.git 36 | $ cd master-python-programming-exercises 37 | ``` 38 | 39 | > Nota: Una vez que termine de descargar, encontrarás la carpeta "exercises" que contiene todos los ejercicios. 40 | 41 | 3. Comienza con los ejercicios ejecutando los siguientes comandos en el mismo nivel que tu archivo learn.json: 42 | 43 | ```bash 44 | $ pip3 install pytest==6.2.5 pytest-testdox mock 45 | $ learnpack start 46 | ``` 47 | 48 | 49 | ## ¿Cómo están organizados los ejercicios? 50 | 51 | Cada ejercicio es un pequeño proyecto en Python que contiene los siguientes archivos: 52 | 53 | 1. **app.py:** representa el archivo de entrada de Python que será ejecutado en el computador. 54 | 2. **README.md:** contiene las instrucciones del ejercicio. 55 | 3. **test.py:** no tienes que abrir este archivo. Contiene los scripts de pruebas del ejercicio. 56 | 57 | > 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. 58 | 59 | # Colaboradores 60 | 61 | Gracias a estas personas maravillosas ([emoji key](https://github.com/kentcdodds/all-contributors#emoji-key)): 62 | 63 | 1. [Alejandro Sanchez (alesanchezr)](https://github.com/alesanchezr), contribución: (programador) 💻, (idea) 🤔, (build-tests) ⚠️, (pull-request-review) 👀, (build-tutorial) ✅, (documentación) 📖 64 | 65 | 2. [Paolo (plucodev)](https://github.com/plucodev), contribución: (bug reports) 🐛, (programador) 💻, (traducción) 🌎 66 | 67 | 3. [Marco Gómez (marcogonzalo)](https://github.com/marcogonzalo), contribution: (bug reports) 🐛, (translation) 🌎 68 | 69 | Este proyecto sigue la especificación [all-contributors](https://github.com/kentcdodds/all-contributors). ¡Todas las contribuciones son bienvenidas! 70 | 71 | Este y otros ejercicios son usados para [aprender a programar](https://4geeksacademy.com/es/aprender-a-programar/aprender-a-programar-desde-cero) por parte de los alumnos de 4Geeks Academy [Coding Bootcamp](https://4geeksacademy.com/us/coding-bootcamp) realizado por [Alejandro Sánchez](https://twitter.com/alesanchezr) y muchos otros contribuyentes. Conoce más sobre nuestros [Cursos de Programación](https://4geeksacademy.com/es/curso-de-programacion-desde-cero?lang=es) para convertirte en [Full Stack Developer](https://4geeksacademy.com/es/coding-bootcamps/desarrollador-full-stack/?lang=es), o nuestro [Data Science Bootcamp](https://4geeksacademy.com/es/coding-bootcamps/curso-datascience-machine-learning). 72 | 73 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | # 🐍 Mastering Python Algorithms Tutorial 3 | 4 | By [@alesanchezr](https://twitter.com/alesanchezr) and [other contributors](https://github.com/4GeeksAcademy//master-python-programming-exercises/graphs/contributors) at [4Geeks Academy](http://4geeksacademy.co/) 5 | 6 | 7 | 8 | 9 | 10 | *Estas instrucciones [están disponibles en 🇪🇸 español](https://github.com/4GeeksAcademy/master-python-programming-exercises/blob/master/README.es.md) :es:* 11 | 12 | After you finish the begginers, functions, and loop series, this series will really prepare you for your next job or any other programming challenge. Practice everything there is to know to build algorithms with Python, from intermediate to hard challenges. 13 | 14 | The entire tutorial is 👆 interactive and ✅ auto-graded. 15 | 16 | These exercises were built in collaboration, we need you! If you find any bugs or misspellings, please contribute and report them. 17 | 18 | 19 | 20 | ## One click installation (recommended): 21 | 22 | You can open these exercises in just a few seconds by clicking: [Open in Codespaces](https://codespaces.new/?repo=4GeeksAcademy/master-python-programming-exercises) (recommended) or [Open in Gitpod](https://gitpod.io#https://github.com/4GeeksAcademy/master-python-programming-exercises). 23 | 24 | > 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` 25 | 26 | ## Local Installation 27 | 28 | 1. Make sure you have [LearnPack](https://learnpack.co) installed, node.js version 14+, and Python version 3+. This is the command to install LearnPack: 29 | 30 | ```bash 31 | npm i @learnpack/learnpack@2.1.20 -g && learnpack plugins:install @learnpack/python@1.0.0 32 | ``` 33 | 34 | 2. Clone or download this repository in your local environment. 35 | 36 | ```bash 37 | $ git clone https://github.com/4GeeksAcademy/master-python-programming-exercises.git 38 | $ cd master-python-programming-exercises 39 | ``` 40 | 41 | > Note: Once you finish downloading, you will find an "exercises" folder that contains all the exercises within. 42 | 43 | 3. Start the tutorial/exercises by running the following command at the same level your learn.json file is: 44 | 45 | ```bash 46 | $ pip3 install pytest==6.2.5 pytest-testdox mock 47 | $ learnpack start 48 | ``` 49 | 50 | 51 | 52 | ## How are the exercises organized? 53 | 54 | Each exercise is a small Python application containing the following files: 55 | 56 | 1. **app.py:** represents the entry Python file that will be executed by the computer. 57 | 2. **README.md:** contains exercise instructions. 58 | 3. **test.py:** you don't have to open this file, it contains the testing script for the exercise. 59 | 60 | > 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. 61 | 62 | ## Contributors 63 | 64 | Thanks goes to these wonderful people ([emoji key](https://github.com/kentcdodds/all-contributors#emoji-key)): 65 | 66 | 1. [Alejandro Sanchez (alesanchezr)](https://github.com/alesanchezr), contribution: (coder) 💻, (idea) 🤔, (build-tests) ⚠️, (pull-request-review) 👀, (build-tutorial) ✅, (documentation) 📖 67 | 68 | 2. [Paolo (plucodev)](https://github.com/plucodev), contribution: (bug reports) 🐛, (coder) 💻, (translation) 🌎 69 | 70 | 3. [Marco Gómez (marcogonzalo)](https://github.com/marcogonzalo), contribution: (bug reports) 🐛, (translation) 🌎 71 | 72 | This project follows the [all-contributors](https://github.com/kentcdodds/all-contributors) specification. Contributions of any kind are welcome! 73 | 74 | 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](https://twitter.com/alesanchezr) 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 [Data Science Bootcamp](https://4geeksacademy.com/us/coding-bootcamps/datascience-machine-learning). 75 | -------------------------------------------------------------------------------- /badge-master-python.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/4GeeksAcademy/master-python-programming-exercises/c5d0bdcb7da8f3b57c03268b301dd8760dd9506a/badge-master-python.png -------------------------------------------------------------------------------- /exercises/000-welcome/README.es.md: -------------------------------------------------------------------------------- 1 | # Welcome to Python! 2 | 3 | ¡¡Nos entusiasma mucho tenerte aquí!! 🎉 😂 4 | 5 | Este es el último de una serie de ejercicios publicados para practicar Python desde cero por [@alesanchezr](https://twitter.com/alesanchezr) y [4GeeksAcademy](https://4geeksacademy.com). 6 | 7 | Si no has completado los otros tutoriales te recomiendo que empieces por allí: 8 | 9 | 1. [Python para principiantes](https://github.com/4GeeksAcademy/python-beginner-programming-exercises). 10 | 11 | 2. [Practica Funciones](https://github.com/4GeeksAcademy/python-functions-programming-exercises). 12 | 13 | 3. [Practica Listas y Bucles](https://github.com/4GeeksAcademy/python-lists-loops-programming-exercises). 14 | 15 | Presiona `Next →` en la esquina superior derecha cuando quieras empezar. 16 | -------------------------------------------------------------------------------- /exercises/000-welcome/README.md: -------------------------------------------------------------------------------- 1 | # Welcome to Python! 2 | 3 | We are very excited to have you here !! 🎉 😂 4 | 5 | This is the last series of exercises in a list of Python interactive tutorials published by [@alesanchezr](https://twitter.com/alesanchezr) with [4GeeksAcademy](https://4geeksacademy.com). 6 | 7 | If you have not completed them, and you are new to Python, I strongly recommend you start with: 8 | 9 | 1. [Python for beginners](https://github.com/4GeeksAcademy/python-beginner-programming-exercises). 10 | 11 | 2. [Practice Functions](https://github.com/4GeeksAcademy/python-functions-programming-exercises). 12 | 13 | 3. [Practice Loops and Lists](https://github.com/4GeeksAcademy/python-lists-loops-programming-exercises). 14 | 15 | Click `Next →` on the top right of these instructions when you are ready to start. 16 | -------------------------------------------------------------------------------- /exercises/001-hello_world/README.es.md: -------------------------------------------------------------------------------- 1 | # `001` hello world 2 | 3 | En Python, usamos `print` para hacer que el computador escriba cualquier cosa que queramos (el contenido de una variable, una cadena de texto dada, etc.) en algo llamado "la consola". 4 | 5 | Cada lenguaje tiene una consola, ya que al principio era la única forma de interactuar con los usuarios (antes de que llegaran Windows, Linux o macOS). 6 | 7 | Hoy en día, la impresión en la consola se utiliza, sobre todo, como herramienta de monitoreo y depuración, ideal para dejar un rastro del contenido de las variables durante la ejecución del programa. 8 | 9 | ## 📝 Instrucciones: 10 | 11 | 1. Usa la función `print()` para escribir `"Hello World"` en la consola. Siéntete libre de intentar otras cosas también. 12 | 13 | ## 📎 Ejemplo: 14 | 15 | ```py 16 | print("How are you?") 17 | ``` 18 | 19 | ## 💡 Pista: 20 | 21 | + Video de 2 minutos sobre [la consola](https://www.youtube.com/watch?v=vROGBvX_MHQ). 22 | -------------------------------------------------------------------------------- /exercises/001-hello_world/README.md: -------------------------------------------------------------------------------- 1 | # `001` hello world 2 | 3 | In Python, we use `print` to make the computer write anything we want (the content of a variable, a given string, etc.) in something called "the console". 4 | 5 | Every language has a console, as it was the only way to interact with the users at the beginning (before Windows, Linux or macOS arrived). 6 | 7 | Today, printing in the console is mostly used as a monitoring and debugging tool, ideal for leaving a trace of the content of variables during the program's execution. 8 | 9 | ## 📝 Instructions: 10 | 11 | 1. Use the `print()` function to print `"Hello World"` on the console. Feel free to try other things as well. 12 | 13 | ## 📎 Example: 14 | 15 | ```py 16 | print("How are you?") 17 | ``` 18 | 19 | ## 💡 Hint: 20 | 21 | + 2 minute video about [the console](https://www.youtube.com/watch?v=vROGBvX_MHQ). 22 | -------------------------------------------------------------------------------- /exercises/001-hello_world/app.py: -------------------------------------------------------------------------------- 1 | # Your code here 2 | -------------------------------------------------------------------------------- /exercises/001-hello_world/solution.hide.py: -------------------------------------------------------------------------------- 1 | # Your code here 2 | print("Hello World") 3 | -------------------------------------------------------------------------------- /exercises/001-hello_world/test.py: -------------------------------------------------------------------------------- 1 | import io, sys, pytest, mock 2 | 3 | @pytest.mark.it('Your code needs to print Hello World on the console') 4 | def test_for_file_output(capsys): 5 | import app 6 | captured = capsys.readouterr() 7 | assert "Hello World\n" == captured.out 8 | -------------------------------------------------------------------------------- /exercises/002-sum_of_three_numbers/README.es.md: -------------------------------------------------------------------------------- 1 | # `002` sum of three numbers 2 | 3 | ## 📝 Instrucciones: 4 | 5 | 1. Teniendo tres números de entrada, imprime su suma. Cada número va en una línea aparte. 6 | 7 | ## 📎 Ejemplo de entrada: 8 | 9 | ```py 10 | 2 11 | 3 12 | 6 13 | ``` 14 | 15 | ## 📎 Ejemplo de salida: 16 | 17 | ```py 18 | 11 19 | ``` 20 | 21 | -------------------------------------------------------------------------------- /exercises/002-sum_of_three_numbers/README.md: -------------------------------------------------------------------------------- 1 | # `002` sum of three numbers 2 | 3 | ## 📝 Instructions: 4 | 5 | 1. Taking 3 numbers from the input, print their sum. Every number is given on a separate line. 6 | 7 | ## 📎 Example input: 8 | 9 | ```py 10 | 2 11 | 3 12 | 6 13 | ``` 14 | 15 | ## 📎 Example output: 16 | 17 | ```py 18 | 11 19 | ``` 20 | 21 | -------------------------------------------------------------------------------- /exercises/002-sum_of_three_numbers/app.py: -------------------------------------------------------------------------------- 1 | # Sum all three input numbers and print on the console the result 2 | first_number = int(input("First input: ")) 3 | second_number = int(input("Second input: ")) 4 | third_number = int(input("Third input: ")) 5 | 6 | 7 | # Print here the sum of all three inputs 8 | print(first_number+second_number) 9 | -------------------------------------------------------------------------------- /exercises/002-sum_of_three_numbers/solution.hide.py: -------------------------------------------------------------------------------- 1 | # Sum all three input numbers and print on the console the result 2 | first_number = int(input("First input: ")) 3 | second_number = int(input("Second input: ")) 4 | third_number = int(input("Third input: ")) 5 | 6 | 7 | # Print here the sum of all three inputs 8 | print(first_number+second_number+third_number) 9 | -------------------------------------------------------------------------------- /exercises/002-sum_of_three_numbers/test.py: -------------------------------------------------------------------------------- 1 | import pytest, io, sys, json, mock, re, os 2 | path = os.path.dirname(os.path.abspath(__file__))+'/app.py' 3 | 4 | @pytest.mark.it("You need to use the print() method") 5 | def test_use_print(): 6 | with open(path, 'r') as content_file: 7 | content = content_file.read() 8 | regex = re.compile(r"print(\s)*\(") 9 | assert bool(regex.search(content)) == True 10 | 11 | @pytest.mark.it('The solution should return the expected output. Tested with 2, 3, 6') 12 | def test_sum_expected_inputs(capsys, app): 13 | 14 | fake_input = ["2","3","6"] #fake input 15 | with mock.patch('builtins.input', lambda x: fake_input.pop()): 16 | app() 17 | captured = capsys.readouterr() 18 | assert captured.out == "11\n" 19 | 20 | @pytest.mark.it('The solution must sum all entries. Tested with 0, 3, 7') 21 | def test_sum_another_inputs(capsys, app): 22 | 23 | fake_input = ["0","3","7"] #fake input 24 | with mock.patch('builtins.input', lambda x: fake_input.pop()): 25 | app() 26 | captured = capsys.readouterr() 27 | assert captured.out == "10\n" 28 | 29 | @pytest.mark.it('The solution must sum all entries. Tested with 0, 0, 0') 30 | def test_sum_with_zero(capsys, app): 31 | 32 | fake_input = ["0","0","0"] #fake input 33 | with mock.patch('builtins.input', lambda x: fake_input.pop()): 34 | app() 35 | captured = capsys.readouterr() 36 | assert captured.out == "0\n" 37 | 38 | 39 | 40 | 41 | -------------------------------------------------------------------------------- /exercises/003-area_of_right_triangle/README.es.md: -------------------------------------------------------------------------------- 1 | # `003` area of right triangle 2 | 3 | ## 📝 Instrucciones: 4 | 5 | 1. Completa la función `area_of_triangle()` para que tome el largo de la base y la altura de un triángulo rectángulo e imprima su área. 6 | 7 | ![triángulo rectángulo fórmula del área](http://i.imgur.com/6EkzVxA.jpg) 8 | 9 | ## 📎 Ejemplo: 10 | 11 | ```py 12 | area_of_triangle(3,5) 13 | # Salida --> 7.5 14 | ``` 15 | 16 | ## 💡 Pistas: 17 | 18 | + Si no sabes por donde empezar este ejercicio, por favor, revisa la teoría en esta lección: https://snakify.org/lessons/print_input_numbers/ 19 | 20 | + También puedes intentar paso a paso con trozos de la teoría: https://snakify.org/lessons/print_input_numbers/steps/1/ 21 | -------------------------------------------------------------------------------- /exercises/003-area_of_right_triangle/README.md: -------------------------------------------------------------------------------- 1 | # `003` area of right triangle 2 | 3 | ## 📝 Instructions: 4 | 5 | 1. Complete the `area_of_triangle()` function so that it reads the length of the base and the height of a right-angled triangle and prints the area. 6 | 7 | ![right triangle area formula](http://i.imgur.com/6EkzVxA.jpg) 8 | 9 | ## 📎 Example: 10 | 11 | ```py 12 | area_of_triangle(3,5) 13 | # Output --> 7.5 14 | ``` 15 | ## 💡 Hints: 16 | 17 | + If you don't know how to start solving this exercise, please review the theory for this lesson: https://snakify.org/lessons/print_input_numbers/ 18 | 19 | + You may also try step-by-step theory chunks: https://snakify.org/lessons/print_input_numbers/steps/1/ 20 | -------------------------------------------------------------------------------- /exercises/003-area_of_right_triangle/app.py: -------------------------------------------------------------------------------- 1 | # Complete the function to return the area of a triangle 2 | def area_of_triangle(base, height): 3 | # Your code here, please remove the "None" 4 | return None 5 | 6 | # Testing your function 7 | print(area_of_triangle(3, 5)) 8 | -------------------------------------------------------------------------------- /exercises/003-area_of_right_triangle/solution.hide.py: -------------------------------------------------------------------------------- 1 | # Complete the function to return the area of a triangle 2 | def area_of_triangle(base, height): 3 | # Your code here, please remove the "None" 4 | return base * height / 2 5 | 6 | # Testing your function 7 | print(area_of_triangle(3, 5)) 8 | -------------------------------------------------------------------------------- /exercises/003-area_of_right_triangle/test.py: -------------------------------------------------------------------------------- 1 | import io, sys, os, pytest, json, mock 2 | path = os.path.dirname(os.path.abspath(__file__))+'/app.py' 3 | 4 | @pytest.mark.it('The function area_of_triangle should exist') 5 | def test_function_exists(capsys, app): 6 | try: 7 | app.area_of_triangle 8 | except AttributeError: 9 | raise AttributeError("The function 'area_of_triangle' should exist on app.py") 10 | 11 | @pytest.mark.it('The function must return something') 12 | def test_function_returns(capsys, app): 13 | result = app.area_of_triangle(1, 2) 14 | assert result != None 15 | 16 | @pytest.mark.it('The function must return a number') 17 | def test_function_return_type(capsys, app): 18 | result = app.area_of_triangle(1,2) 19 | assert type(result) == type(1*2/2) 20 | 21 | @pytest.mark.it('The solution should return the expected output. Testing with 3 and 5') 22 | def test_convert_inputs(capsys, app): 23 | result = app.area_of_triangle(3, 5) 24 | assert result == 7.5 25 | 26 | -------------------------------------------------------------------------------- /exercises/004-hello_harry/README.es.md: -------------------------------------------------------------------------------- 1 | # `004` hello Harry 2 | 3 | ## 📝 Instrucciones: 4 | 5 | 1. Completa la función `hello_name()` para que salude al usuario imprimiendo la palabra `Hello`, luego le agregue una coma, el nombre del usuario y un signo de exclamación después. 6 | 7 | *La salida de tu función debe coincidir estrictamente con la deseada, caracter por caracter. No debe haber ningún espacio entre el nombre y el signo de exclamación.* 8 | 9 | ## 📎 Ejemplo de entrada: 10 | 11 | ```py 12 | hello_name("Harry") 13 | ``` 14 | ## 📎 Ejemplo de salida: 15 | 16 | ```text 17 | Hello, Harry! 18 | ``` 19 | 20 | ## 💡 Pistas: 21 | 22 | + Puedes usar el operador `+` para concatenar dos strings de texto. Repasa la lección para más detalles. 23 | 24 | + Si no sabes por donde empezar este ejercicio, por favor, revisa la teoría en esta lección: https://snakify.org/lessons/print_input_numbers/ 25 | 26 | + También puedes intentar paso a paso con trozos de la teoría: https://snakify.org/lessons/print_input_numbers/steps/1/ 27 | -------------------------------------------------------------------------------- /exercises/004-hello_harry/README.md: -------------------------------------------------------------------------------- 1 | # `004` hello Harry 2 | 3 | ## 📝 Instructions: 4 | 5 | 1. Complete the `hello_name()` function that greets the user by printing the word `Hello`, a comma, the name of the user, and an exclamation mark after it. 6 | 7 | *Your function's output should strictly match the desired one, character by character. There shouldn't be any space between the name and the exclamation mark.* 8 | 9 | ## 📎 Example input: 10 | 11 | ```py 12 | hello_name("Harry") 13 | ``` 14 | 15 | ## 📎 Example output: 16 | 17 | ```text 18 | Hello, Harry! 19 | ``` 20 | 21 | ## 💡 Hints: 22 | 23 | + You can use `+` operator to concatenate two strings. review the lesson for details. 24 | 25 | + If you don't know how to start solving this assignment, please review the theory for this lesson: https://snakify.org/lessons/print_input_numbers/ 26 | 27 | + You may also try step-by-step theory chunks: https://snakify.org/lessons/print_input_numbers/steps/1/ 28 | -------------------------------------------------------------------------------- /exercises/004-hello_harry/app.py: -------------------------------------------------------------------------------- 1 | # Complete the function below to print the output as per the example 2 | def hello_name(name): 3 | # Your code here 4 | return None 5 | 6 | # Invoke the function with your name as the function's argument 7 | print(hello_name("Bob")) 8 | -------------------------------------------------------------------------------- /exercises/004-hello_harry/solution.hide.py: -------------------------------------------------------------------------------- 1 | # Complete the function below to print the output as per the example 2 | def hello_name(name): 3 | # Your code here 4 | return "Hello, "+name+"!" 5 | 6 | # Invoke the function with your name as the function's argument 7 | print(hello_name("Bob")) 8 | -------------------------------------------------------------------------------- /exercises/004-hello_harry/test.py: -------------------------------------------------------------------------------- 1 | import io, sys, pytest, os, re, mock 2 | 3 | @pytest.mark.it('The function hello_name must exist') 4 | def test_for_functon_existence(capsys, app): 5 | assert callable(app.hello_name) 6 | 7 | @pytest.mark.it('The function must return something') 8 | def test_function_return(capsys, app): 9 | result = app.hello_name('test') 10 | assert result != None 11 | 12 | @pytest.mark.it('The function must return a string') 13 | def test_function_return_type(capsys, app): 14 | result = app.hello_name('test') 15 | assert type(result) == type('') 16 | 17 | @pytest.mark.it('The function hello_name must accept 1 parameter and return the correct output') 18 | def test_for_file_output(capsys, app): 19 | assert app.hello_name('a') == "Hello, a!" -------------------------------------------------------------------------------- /exercises/005-previous_and_next/README.es.md: -------------------------------------------------------------------------------- 1 | # `005` previous and next 2 | 3 | ## 📝 Instrucciones: 4 | 5 | 1. Completa la función `previous_next()` para que lea un número entero y devuelva sus números anteriores y siguientes. 6 | 7 | ## 📎 Ejemplo de entrada: 8 | 9 | ```py 10 | previous_next(179) 11 | ``` 12 | 13 | ## 📎 Ejemplo de salida: 14 | 15 | ```py 16 | (178, 180) 17 | ``` 18 | 19 | ## 💡 Pistas: 20 | 21 | + Puedes devolver múltiples parámetros: `return a, b` 22 | 23 | + Si no sabes por donde partir este ejercicio, por favor revisa la teoría en esta lección: https://snakify.org/lessons/print_input_numbers/ 24 | 25 | + También puedes intentar paso a paso con trozos de la teoría: https://snakify.org/lessons/print_input_numbers/steps/1/ 26 | -------------------------------------------------------------------------------- /exercises/005-previous_and_next/README.md: -------------------------------------------------------------------------------- 1 | # `005` previous and next 2 | 3 | ## 📝 Instructions: 4 | 5 | 1. Complete a function `previous_next()` that reads an integer number and returns its previous and next numbers. 6 | 7 | ## 📎 Example input: 8 | 9 | ```py 10 | previous_next(179) 11 | ``` 12 | 13 | ## 📎 Example output: 14 | 15 | ```py 16 | (178, 180) 17 | ``` 18 | 19 | ## 💡 Hints: 20 | 21 | + You can return multiple parameters: `return a, b` 22 | 23 | + If you don't know how to start solving this assignment, please, review a theory for this lesson: https://snakify.org/lessons/print_input_numbers/ 24 | 25 | + You may also try step-by-step theory chunks: https://snakify.org/lessons/print_input_numbers/steps/1/ 26 | -------------------------------------------------------------------------------- /exercises/005-previous_and_next/app.py: -------------------------------------------------------------------------------- 1 | # Complete the function to return the previous and next number of a given number 2 | def previous_next(num): 3 | # Your code here 4 | return None 5 | 6 | 7 | # Invoke the function with any integer as its argument 8 | print(previous_next(179)) 9 | -------------------------------------------------------------------------------- /exercises/005-previous_and_next/solution.hide.py: -------------------------------------------------------------------------------- 1 | # Complete the function to return the previous and next number of a given number 2 | def previous_next(num): 3 | # Your code here 4 | return (num-1, num+1) 5 | 6 | 7 | # Invoke the function with any integer as its argument 8 | print(previous_next(179)) 9 | -------------------------------------------------------------------------------- /exercises/005-previous_and_next/test.py: -------------------------------------------------------------------------------- 1 | import io, sys, pytest, os, re, mock 2 | 3 | @pytest.mark.it('The function previous_next must exist') 4 | def test_for_functon_existence(capsys, app): 5 | assert callable(app.previous_next) 6 | 7 | @pytest.mark.it('The function must return something') 8 | def test_function_return(capsys, app): 9 | assert app.previous_next(6) != None 10 | 11 | @pytest.mark.it('The function should return a tuple') 12 | def test_function_return_type(capsys, app): 13 | result = app.previous_next(6) 14 | assert type(result) == type((1,2)) 15 | 16 | @pytest.mark.it('The function previous_next must return the correct output') 17 | def test_for_file_output(capsys, app): 18 | assert app.previous_next(6) == (5, 7) 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | -------------------------------------------------------------------------------- /exercises/006-apple_sharing/README.es.md: -------------------------------------------------------------------------------- 1 | # `006` apple sharing 2 | 3 | ## 📝 Instrucciones: 4 | 5 | 1. `N` estudiantes cogen `K` manzanas y las distribuyen entre ellos de manera uniforme. La parte restante (indivisible) permanece en la cesta. ¿Cuántas manzanas recibirá cada estudiante? y ¿Cuántas manzanas quedarán en la cesta? *Esta función lee los números `N` y `K` y debería devolver la respuesta a ambas preguntas.* 6 | 7 | ## 📎 Ejemplo de entrada: 8 | 9 | ```py 10 | apple_sharing(6, 50) 11 | ``` 12 | 13 | ## 📎 Ejemplo de salida: 14 | 15 | ```py 16 | (8, 2) 17 | ``` 18 | 19 | ## 💡 Pistas: 20 | 21 | + Puedes devolver múltiples parámetros: `return a, b` 22 | 23 | + Si no sabes por donde partir este ejercicio, por favor, revisa la teoría en esta lección: https://snakify.org/lessons/print_input_numbers/ 24 | 25 | + También puedes intentar paso a paso con trozos de la teoría: https://snakify.org/lessons/print_input_numbers/steps/1/ 26 | -------------------------------------------------------------------------------- /exercises/006-apple_sharing/README.md: -------------------------------------------------------------------------------- 1 | # `006` apple sharing 2 | 3 | ## 📝 Instructions: 4 | 5 | 1. `N` students take `K` apples and distribute them among each other evenly. The remaining (indivisible) part remains in the basket. How many apples will each single student get, and how many apples will remain in the basket? *The function reads the numbers `N` and `K` and it should return the two answers for the questions above.* 6 | 7 | ## 📎 Example input: 8 | 9 | ```py 10 | apple_sharing(6, 50) 11 | ``` 12 | 13 | ## 📎 Example output: 14 | 15 | ```py 16 | (8, 2) 17 | ``` 18 | 19 | ## 💡 Hints: 20 | 21 | + You can return multiple parameters: `return a, b` 22 | 23 | + If you don't know how to start solving this assignment, please review the theory for this lesson: https://snakify.org/lessons/print_input_numbers/ 24 | 25 | + You may also try step-by-step theory chunks: https://snakify.org/lessons/print_input_numbers/steps/1/ 26 | -------------------------------------------------------------------------------- /exercises/006-apple_sharing/app.py: -------------------------------------------------------------------------------- 1 | def apple_sharing(n,k): 2 | # Your code here 3 | return None 4 | 5 | 6 | print(apple_sharing(6,50)) 7 | -------------------------------------------------------------------------------- /exercises/006-apple_sharing/solution.hide.py: -------------------------------------------------------------------------------- 1 | def apple_sharing(n,k): 2 | # Your code here 3 | return (round(k/n), k%n) 4 | 5 | 6 | print(apple_sharing(6,50)) 7 | -------------------------------------------------------------------------------- /exercises/006-apple_sharing/test.py: -------------------------------------------------------------------------------- 1 | import io, sys, pytest, os, re, mock 2 | 3 | @pytest.mark.it('The function apple_sharing must exist') 4 | def test_for_functon_existence(capsys, app): 5 | assert callable(app.apple_sharing) 6 | 7 | @pytest.mark.it('The function must return something') 8 | def test_function_return(capsys, app): 9 | assert app.apple_sharing(10, 54) != None 10 | 11 | @pytest.mark.it('The function must return a tuple') 12 | def test_function_return_type(capsys, app): 13 | result = app.apple_sharing(10, 54) 14 | assert type(result) == type((1,2)) 15 | 16 | @pytest.mark.it('The function apple_sharing must return the correct output') 17 | def test_for_file_output(capsys, app): 18 | assert app.apple_sharing(10, 54) == (54//10, 54%10) 19 | 20 | 21 | -------------------------------------------------------------------------------- /exercises/006.1-square_value_of_number/README.es.md: -------------------------------------------------------------------------------- 1 | # `006.1` square value of number 2 | 3 | ## 📝 Instrucciones: 4 | 5 | 1. Escribe una función llamada `square()` que calcule el valor al cuadrado de un número. 6 | 7 | ## 📎 Ejemplo de entrada: 8 | 9 | ```py 10 | square(6) 11 | ``` 12 | 13 | ## 📎 Ejemplo de salida: 14 | 15 | ```py 16 | 36 17 | ``` 18 | 19 | ## 💡 Pista: 20 | 21 | + Usa el operador `**`. 22 | -------------------------------------------------------------------------------- /exercises/006.1-square_value_of_number/README.md: -------------------------------------------------------------------------------- 1 | # `006.1` square value of number 2 | 3 | ## 📝 Instructions: 4 | 5 | 1. Write a function called `square()` that calculates the square value of a number. 6 | 7 | ## 📎 Example input: 8 | 9 | ```py 10 | square(6) 11 | ``` 12 | 13 | ## 📎 Example output: 14 | 15 | ```py 16 | 36 17 | ``` 18 | 19 | ## 💡 Hint: 20 | 21 | + Using the `**` operator. 22 | -------------------------------------------------------------------------------- /exercises/006.1-square_value_of_number/app.py: -------------------------------------------------------------------------------- 1 | def square(num): 2 | # Your code here 3 | return None 4 | 5 | print(square(6)) 6 | -------------------------------------------------------------------------------- /exercises/006.1-square_value_of_number/solution.hide.py: -------------------------------------------------------------------------------- 1 | def square(num): 2 | # Your code here 3 | return num ** 2 4 | 5 | print(square(6)) 6 | -------------------------------------------------------------------------------- /exercises/006.1-square_value_of_number/test.py: -------------------------------------------------------------------------------- 1 | import io, sys, pytest, os, re, mock 2 | 3 | @pytest.mark.it('The function square must exist') 4 | def test_for_functon_existence(capsys, app): 5 | assert callable(app.square) 6 | 7 | @pytest.mark.it('The function must return something') 8 | def test_function_return(capsys, app): 9 | assert app.square(2) != None 10 | 11 | @pytest.mark.it('The function must return a number') 12 | def test_function_return_type(capsys, app): 13 | result = app.square(6) 14 | assert type(result) == type(1) 15 | 16 | @pytest.mark.it('The function should return the square of the given number') 17 | def test_for_file_output(capsys, app): 18 | assert app.square(6) == 6*6 19 | 20 | @pytest.mark.it('The function should return the square of the given number. Testing with 47') 21 | def test_for_file_output(capsys, app): 22 | assert app.square(47) == 47*47 23 | 24 | @pytest.mark.it("Use the ** operator") 25 | def test_operator(): 26 | path = os.path.dirname(os.path.abspath(__file__))+'/app.py' 27 | with open(path, 'r') as content_file: 28 | content = content_file.read() 29 | regex = re.compile(r"\*\*") 30 | assert bool(regex.search(content)) == True 31 | 32 | 33 | -------------------------------------------------------------------------------- /exercises/007-hours_and_minutes/README.es.md: -------------------------------------------------------------------------------- 1 | # `007` Hours and minutes 2 | 3 | Queremos que con la función `hours_minutes` que hemos previsto para ti, nos digas cuánto tiempo ha pasado en horas y minutos desde entonces con los segundos que se introduzcan como parámetro. 4 | 5 | ## 📝 Instrucciones: 6 | 7 | 1. Completa la función para que retorne el resultado esperado. 8 | 9 | 2. Realiza dos cálculos con los segundos que se pasan por parámetro en la función para que uno calcule la hora según los segundos que han pasado y el otro para saber los minutos `(horas, minutos)`. 10 | 11 | ## 📎 Ejemplo 1: 12 | 13 | ```py 14 | output = hours_minutes(3900) 15 | print(output) # (1, 5) 16 | ``` 17 | 18 | ## 📎 Ejemplo 2: 19 | 20 | ```py 21 | output = hours_minutes(60) 22 | print(output) # (0, 1) 23 | ``` 24 | 25 | ## 💡 Pista: 26 | 27 | + Recuerda cuantos segundos hay en una hora (3600) y cuantos segundos en un minuto (60). 28 | -------------------------------------------------------------------------------- /exercises/007-hours_and_minutes/README.md: -------------------------------------------------------------------------------- 1 | # `007` Hours and Minutes 2 | 3 | Complete the function `hours_minutes` to transform the given number of seconds into hours and minutes, indicating how much time has passed since then. 4 | 5 | ## 📝 Instructions: 6 | 7 | 1. Complete the function to return the expected result. 8 | 9 | 2. Perform two calculations based on the input parameter representing seconds. One calculation should determine the time elapsed in hours, while the other should indicate the time in minutes `(hours, minutes)`. 10 | 11 | ## 📎 Example 1: 12 | 13 | ```py 14 | output = hours_minutes(3900) 15 | print(output) # (1, 5) 16 | ``` 17 | 18 | ## 📎 Example 2: 19 | 20 | ```py 21 | output = hours_minutes(60) 22 | print(output) # (0, 1) 23 | ``` 24 | 25 | ## 💡 Hint: 26 | 27 | + Remember how many seconds there are in an hour (3600) and how many seconds in a minute (60). 28 | -------------------------------------------------------------------------------- /exercises/007-hours_and_minutes/app.py: -------------------------------------------------------------------------------- 1 | def hours_minutes(seconds): 2 | # Your code here 3 | return None 4 | 5 | # Invoke the function and pass any integer as its argument 6 | print(hours_minutes(3900)) 7 | -------------------------------------------------------------------------------- /exercises/007-hours_and_minutes/solution.hide.py: -------------------------------------------------------------------------------- 1 | def hours_minutes(seconds): 2 | # Your code here 3 | hours = seconds // 3600 4 | remaining_seconds = seconds % 3600 5 | minutes = remaining_seconds // 60 6 | return (hours, minutes) 7 | 8 | # Invoke the function and pass any integer as its argument 9 | print(hours_minutes(3900)) 10 | -------------------------------------------------------------------------------- /exercises/007-hours_and_minutes/test.py: -------------------------------------------------------------------------------- 1 | import io, sys, pytest, os, re, mock 2 | 3 | @pytest.mark.it('The function hours_minutes must exist') 4 | def test_for_functon_existence(capsys, app): 5 | assert callable(app.hours_minutes) 6 | 7 | @pytest.mark.it('The function must return something') 8 | def test_function_return(capsys, app): 9 | assert app.hours_minutes(60) != None 10 | 11 | @pytest.mark.it('The function must return a tuple') 12 | def test_function_return_type(capsys, app): 13 | result = app.hours_minutes(60) 14 | assert type(result) == type((1,2)) 15 | 16 | @pytest.mark.it('The function must return a tuple with numbers') 17 | def test_for_file_output(capsys, app): 18 | result = app.hours_minutes(60) 19 | assert type(result[0]) == type(1) and type(result[1]) == type(1) 20 | 21 | @pytest.mark.it('The function hours_minutes must return the correct output for 60 secs') 22 | def test_for_file_output(capsys, app): 23 | assert app.hours_minutes(60) == (0, 1) 24 | 25 | @pytest.mark.it('The function hours_minutes must return the correct output for 3900 secs') 26 | def test_for_file_output(capsys, app): 27 | assert app.hours_minutes(3900) == (1, 5) 28 | 29 | 30 | @pytest.mark.it('The function hours_minutes must return the correct output for 4500 secs') 31 | def test_for_file_output(capsys, app): 32 | assert app.hours_minutes(4500) == (1, 15) 33 | 34 | 35 | @pytest.mark.it('The function hours_minutes must return the correct output for 7320 secs') 36 | def test_for_file_output(capsys, app): 37 | assert app.hours_minutes(7320) == (2, 2) 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | -------------------------------------------------------------------------------- /exercises/008-two_timestamps/README.es.md: -------------------------------------------------------------------------------- 1 | # `008` two timestamps 2 | 3 | ## 📝 Instrucciones: 4 | 5 | 1. Dadas dos marcas de tiempo del mismo día: un número de horas, minutos y segundos para ambas marcas de tiempo. El momento de la primera marca de tiempo ocurrió antes del momento de la segunda. Calcula cuántos segundos pasaron entre ellas. 6 | 7 | ## 📎 Ejemplo 1: 8 | 9 | ```py 10 | output = two_timestamp(1,1,1,2,2,2) 11 | print(output) # 3661 12 | ``` 13 | 14 | ## 📎 Ejemplo 2: 15 | 16 | ```py 17 | output = two_timestamp(1,2,30,1,3,20) 18 | print(output) # 50 19 | ``` 20 | -------------------------------------------------------------------------------- /exercises/008-two_timestamps/README.md: -------------------------------------------------------------------------------- 1 | # `008` two timestamps 2 | 3 | ## 📝 Instructions: 4 | 5 | 1. Given two timestamps of the same day: a number of hours, minutes and seconds for both of the timestamps. The moment of the first timestamp happened before the moment of the second one. Calculate how many seconds passed between them. 6 | 7 | ## 📎 Example 1: 8 | 9 | ```py 10 | output = two_timestamp(1,1,1,2,2,2) 11 | print(output) # 3661 12 | ``` 13 | 14 | ## 📎 Example 2: 15 | 16 | ```py 17 | output = two_timestamp(1,2,30,1,3,20) 18 | print(output) # 50 19 | ``` 20 | -------------------------------------------------------------------------------- /exercises/008-two_timestamps/app.py: -------------------------------------------------------------------------------- 1 | def two_timestamp(hr1, min1, sec1, hr2, min2, sec2): 2 | # Your code here 3 | return None 4 | 5 | 6 | # Invoke the function and pass two timestamps(6 intergers) as its arguments 7 | print(two_timestamp(1,1,1,2,2,2)) 8 | -------------------------------------------------------------------------------- /exercises/008-two_timestamps/solution.hide.py: -------------------------------------------------------------------------------- 1 | def two_timestamp(hr1, min1, sec1, hr2, min2, sec2): 2 | # Your code here 3 | first_hour = hr1 * 3600 4 | first_min = min1 * 60 5 | final_first = first_hour + first_min + sec1 6 | second_hour = hr2 * 3600 7 | second_min = min2 * 60 8 | final_second = second_hour + second_min + sec2 9 | 10 | return final_second - final_first 11 | 12 | # Invoke the function and pass two timestamps(6 integers) as its arguments 13 | print(two_timestamp(1, 1, 1, 2, 2, 2)) 14 | -------------------------------------------------------------------------------- /exercises/008-two_timestamps/test.py: -------------------------------------------------------------------------------- 1 | import io, sys, pytest, os, re, mock 2 | 3 | @pytest.mark.it('The function two_timestamp must exist') 4 | def test_for_functon_existence(capsys, app): 5 | assert callable(app.two_timestamp) 6 | 7 | @pytest.mark.it('The function must return something') 8 | def test_function_return(capsys, app): 9 | result = app.two_timestamp(1,2,30,4,3,20) 10 | assert result != None 11 | 12 | @pytest.mark.it('The function must return a number') 13 | def test_function_return_type(capsys, app): 14 | result = app.two_timestamp(1,2,30,4,3,20) 15 | assert type(result) == type(1) 16 | 17 | @pytest.mark.it('We tried passing (1,2,30,4,3,20) as parameters and the function did not return 10850. Keep Trying!') 18 | def test_for_file_output(capsys, app): 19 | assert app.two_timestamp(1,2,30,4,3,20) == ( (3 * 60) + (4 * 3600) + 20 )- ((2 * 60) + (1 * 3600) + 30) 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | -------------------------------------------------------------------------------- /exercises/009-two_digits/README.es.md: -------------------------------------------------------------------------------- 1 | # `009` two digits 2 | 3 | ## 📝 Instrucciones: 4 | 5 | 1. Crea una función llamada `two_digits()`. Dado un entero de dos dígitos, `two_digits()` devuelve su dígito izquierdo (las decenas) y luego su dígito derecho (las unidades). 6 | 7 | ## 📎 Ejemplo de entrada: 8 | 9 | ```py 10 | two_digits(79) 11 | ``` 12 | 13 | ## 📎 Ejemplo de salida: 14 | 15 | ```py 16 | (7, 9) 17 | ``` 18 | 19 | ## 💡 Pista: 20 | 21 | + Utiliza el operador de división de enteros `//` para obtener el dígito de las decenas y el operador de resto `%` para obtener el dígito de las unidades. 22 | -------------------------------------------------------------------------------- /exercises/009-two_digits/README.md: -------------------------------------------------------------------------------- 1 | # `009` two digits 2 | 3 | ## 📝 Instructions: 4 | 5 | 1. Create a function named `two_digits()`. Given a two-digit integer, `two_digits()` returns its left digit (the tens digit) and then its right digit (the units digit). 6 | 7 | ## 📎 Example input: 8 | 9 | ```py 10 | two_digits(79) 11 | ``` 12 | 13 | ## 📎 Example output: 14 | 15 | ```py 16 | (7, 9) 17 | ``` 18 | 19 | ## 💡 Hint: 20 | 21 | + Use the operator of integer division `//` to obtain the tens digit and the operator of remainder `%` to obtain the ones digit. 22 | -------------------------------------------------------------------------------- /exercises/009-two_digits/app.py: -------------------------------------------------------------------------------- 1 | # Complete the function to return the tens digit and the units digit of any interger 2 | def two_digits(number): 3 | # Your code here 4 | return None 5 | 6 | 7 | # Invoke the function with any two digit integer as its argument 8 | print(two_digits(79)) 9 | -------------------------------------------------------------------------------- /exercises/009-two_digits/solution.hide.py: -------------------------------------------------------------------------------- 1 | # Complete the function to return the tens digit and the units digit of any interger 2 | def two_digits(number): 3 | # Your code here 4 | aux = str(number) 5 | return (int(aux[0]), int(aux[1])) 6 | 7 | 8 | # Invoke the function with any two digit integer as its argument 9 | print(two_digits(79)) 10 | 11 | 12 | ### SOLUTION 2 ### 13 | 14 | # def two_digits(number): 15 | # tens_digit = number // 10 16 | # ones_digit = number % 10 17 | 18 | # return tens_digit, ones_digit 19 | 20 | # print(two_digits(37)) 21 | -------------------------------------------------------------------------------- /exercises/009-two_digits/test.py: -------------------------------------------------------------------------------- 1 | import io, sys, pytest, os, re, mock 2 | 3 | @pytest.mark.it('The function two_digits must exist') 4 | def test_for_functon_existence(capsys, app): 5 | assert callable(app.two_digits) 6 | 7 | @pytest.mark.it('The function must return something') 8 | def test_function_return(capsys, app): 9 | assert app.two_digits(30) != None 10 | 11 | @pytest.mark.it('The function must return a tuple') 12 | def test_function_return_type(capsys, app): 13 | result = app.two_digits(30) 14 | assert type(result) == type((1,2)) 15 | 16 | @pytest.mark.it('The function must return a tuple with numbers') 17 | def test_for_file_output(capsys, app): 18 | result = app.two_digits(30) 19 | assert type(result[0]) == type(1) and type(result[1]) == type(1) 20 | 21 | @pytest.mark.it('The function two_digits must return the left and right digits of a 2 digits integer') 22 | def test_for_file_output(capsys, app): 23 | assert app.two_digits(30) == (3,0) 24 | 25 | @pytest.mark.it('The function two_digits must return the left and right digits of a 2 digits integer. Testing with 45') 26 | def test_for_file_output(capsys, app): 27 | assert app.two_digits(45) == (4,5) 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | -------------------------------------------------------------------------------- /exercises/010-swap_digits/README.es.md: -------------------------------------------------------------------------------- 1 | # `010` swap digits 2 | 3 | ## 📝 Instrucciones: 4 | 5 | 1. Completa una función llamada `swap_digits()`. Dado un número entero de dos dígitos, `swap_digits()` intercambia sus dígitos de posición e imprime el resultado. 6 | 7 | ## 📎 Ejemplo de entrada: 8 | 9 | ```py 10 | swap_digits(79) 11 | ``` 12 | 13 | ## 📎 Ejemplo de salida: 14 | 15 | ```py 16 | 97 17 | ``` 18 | 19 | ## 💡 Pistas: 20 | 21 | + Si no sabes por donde empezar este ejercicio, por favor revisa la teoría en esta lección: https://snakify.org/lessons/integer_float_numbers/ 22 | 23 | + También puedes intentar paso a paso con parte de la teoría: https://snakify.org/lessons/integer_float_numbers/steps/1/ 24 | 25 | + Ten en cuenta que para concatenar dos números puedes transformar su valor en un string con la función `str(number)`. 26 | 27 | + El valor a retornar debe ser un número entero. 28 | -------------------------------------------------------------------------------- /exercises/010-swap_digits/README.md: -------------------------------------------------------------------------------- 1 | # `010` swap digits 2 | 3 | ## 📝 Instructions: 4 | 5 | 1. Complete a function named `swap_digits()`. Given a two-digit integer, `swap_digits()` swaps its digits and print the result. 6 | 7 | ## 📎 Example input: 8 | 9 | ```py 10 | swap_digits(79) 11 | ``` 12 | 13 | ## 📎 Example output: 14 | 15 | ```py 16 | 97 17 | ``` 18 | 19 | ## 💡 Hints: 20 | 21 | + If you don't know how to start solving this assignment, please review the theory for this lesson: https://snakify.org/lessons/integer_float_numbers/ 22 | 23 | + You can also try step-by-step with theory chunks: https://snakify.org/lessons/integer_float_numbers/steps/1/ 24 | 25 | + Note that you need to concatenate two numbers, so you may have to convert them into a string `str(number)`. 26 | 27 | + The function must return an integer. 28 | -------------------------------------------------------------------------------- /exercises/010-swap_digits/app.py: -------------------------------------------------------------------------------- 1 | # Complete the function to return the swapped digits of a given two-digit integer 2 | def swap_digits(num): 3 | # Your code here 4 | return None 5 | 6 | # Invoke the function with any two-digit integer as its argument 7 | print(swap_digits(30)) 8 | -------------------------------------------------------------------------------- /exercises/010-swap_digits/solution.hide.py: -------------------------------------------------------------------------------- 1 | # Complete the function to return the swapped digits of a given two-digit integer 2 | def swap_digits(num): 3 | # Your code here 4 | aux = str(num)[1] + str(num)[0] 5 | return int(aux) 6 | 7 | # Invoke the function with any two-digit integer as its argument 8 | print(swap_digits(30)) 9 | -------------------------------------------------------------------------------- /exercises/010-swap_digits/test.py: -------------------------------------------------------------------------------- 1 | import io, sys, pytest, os, re, mock, app 2 | 3 | @pytest.mark.it('The function swap_digits must exist') 4 | def test_function_exists(): 5 | assert app.swap_digits 6 | 7 | @pytest.mark.it('The function swap_digits must return something') 8 | def test_return_exists(): 9 | assert app.swap_digits(12) != None 10 | 11 | @pytest.mark.it('The function swap_digits should return an integer') 12 | def test_return_integer(): 13 | assert type(app.swap_digits(23)) == type(1) 14 | 15 | @pytest.mark.it('The function swap_digits must swap the digits. Testing with 79') 16 | def test_for_file_output(capsys, app): 17 | assert app.swap_digits(79) == 97 18 | 19 | @pytest.mark.it('The function swap_digits must swap the digits. Testing with 30') 20 | def test_for_file_output_2(capsys, app): 21 | assert app.swap_digits(30) == 3 22 | -------------------------------------------------------------------------------- /exercises/011-last_two_digits/README.es.md: -------------------------------------------------------------------------------- 1 | # `011` last two digits 2 | 3 | ## 📝 Instrucciones: 4 | 5 | 1. Completa la función `last_two_digits()` para que, dado un número entero mayor que `9`, imprima sus últimos dos dígitos. 6 | 7 | ## 📎 Ejemplo de entrada: 8 | 9 | ```py 10 | last_two_digits(1234) 11 | ``` 12 | 13 | ## 📎 Ejemplo de salida: 14 | 15 | ```py 16 | 34 17 | ``` 18 | 19 | ## 💡 Pistas: 20 | 21 | + Si no sabes por donde comenzar este ejercicio, por favor, revisa la teoría en esta lección: https://snakify.org/lessons/integer_float_numbers/ 22 | 23 | + También puedes intentar paso a paso con trozos de la teoría: https://snakify.org/lessons/integer_float_numbers/steps/1/ 24 | -------------------------------------------------------------------------------- /exercises/011-last_two_digits/README.md: -------------------------------------------------------------------------------- 1 | # `011` last two digits 2 | 3 | ## 📝 Instructions: 4 | 5 | 1. Complete the `last_two_digits()` function. Given an integer greater than `9`, `last_two_digits()` prints its last two digits. 6 | 7 | ## 📎 Example input: 8 | 9 | ```py 10 | last_two_digits(1234) 11 | ``` 12 | 13 | ## 📎 Example output: 14 | 15 | ```py 16 | 34 17 | ``` 18 | 19 | ## 💡 Hints: 20 | 21 | + If you don't know how to start solving this assignment, please review the theory for this lesson: https://snakify.org/lessons/integer_float_numbers/ 22 | 23 | + You may also try step-by-step theory chunks: https://snakify.org/lessons/integer_float_numbers/steps/1/ 24 | -------------------------------------------------------------------------------- /exercises/011-last_two_digits/app.py: -------------------------------------------------------------------------------- 1 | # Complete the function to print the last two digits of an integer greater than 9 2 | def last_two_digits(num): 3 | return None 4 | 5 | # Invoke the function with any integer greater than 9 6 | print(last_two_digits()) 7 | -------------------------------------------------------------------------------- /exercises/011-last_two_digits/solution.hide.py: -------------------------------------------------------------------------------- 1 | # Complete the function to print the last two digits of an integer greater than 9 2 | def last_two_digits(num): 3 | if num > 9: return int(str(num)[-2:]) 4 | else: return num 5 | 6 | # Invoke the function with any integer greater than 9 7 | print(last_two_digits(212)) 8 | -------------------------------------------------------------------------------- /exercises/011-last_two_digits/test.py: -------------------------------------------------------------------------------- 1 | import io, sys, pytest, os, re, mock 2 | 3 | @pytest.mark.it('The function last_two_digits must exist') 4 | def test_for_functon_existence(capsys, app): 5 | assert callable(app.last_two_digits) 6 | 7 | @pytest.mark.it('The function must return something') 8 | def test_for_return(capsys, app): 9 | assert app.last_two_digits(30) != None 10 | 11 | @pytest.mark.it('The function must return a number') 12 | def test_for_output_type(capsys, app): 13 | assert type(app.last_two_digits(30)) == type(1) 14 | 15 | @pytest.mark.it('The function last_two_digits must return only the last 2 digits of an integer greater than 9') 16 | def test_for_file_output(capsys, app): 17 | if app.last_two_digits(30) > 9: 18 | assert app.last_two_digits(30) == int(str(30)[-2:]) 19 | 20 | 21 | 22 | 23 | 24 | -------------------------------------------------------------------------------- /exercises/012-tens_digit/README.es.md: -------------------------------------------------------------------------------- 1 | # `012` tens digits 2 | 3 | ## 📝 Instrucciones: 4 | 5 | 1. Completa la función `tens_digit()` para que dado un número entero, retorne sus decenas. 6 | 7 | ## 📎 Ejemplo 1: 8 | 9 | ```py 10 | output = tens_digit(1234) 11 | print(output) # 3 12 | ``` 13 | 14 | ## 📎 Ejemplo 2: 15 | 16 | ```py 17 | output = tens_digit(179) 18 | print(output) # 7 19 | ``` 20 | 21 | ## 💡 Pistas: 22 | 23 | + Si no sabes por donde comenzar este ejercicio, por favor, revisa la teoría en esta lección: https://snakify.org/lessons/integer_float_numbers/ 24 | 25 | + También puedes intentar paso a paso con trozos de la teoría: https://snakify.org/lessons/integer_float_numbers/steps/1/ 26 | -------------------------------------------------------------------------------- /exercises/012-tens_digit/README.md: -------------------------------------------------------------------------------- 1 | # `012` tens digits 2 | 3 | ## 📝 Instructions: 4 | 5 | 1. Complete the `tens_digit()` function. Given an integer, `tens_digit()` returns its tens digit. 6 | 7 | ## 📎 Example 1: 8 | 9 | ```py 10 | output = tens_digit(1234) 11 | print(output) # 3 12 | ``` 13 | 14 | ## 📎 Example 2: 15 | 16 | ```py 17 | output = tens_digit(179) 18 | print(output) # 7 19 | ``` 20 | 21 | ## 💡 Hints: 22 | 23 | + If you don't know how to start solving this assignment, please review the theory for this lesson: https://snakify.org/lessons/integer_float_numbers/ 24 | 25 | + You may also try step-by-step theory chunks: https://snakify.org/lessons/integer_float_numbers/steps/1/ 26 | -------------------------------------------------------------------------------- /exercises/012-tens_digit/app.py: -------------------------------------------------------------------------------- 1 | # Complete the function to return the tens digit of a given integer 2 | def tens_digit(num): 3 | return None 4 | 5 | 6 | # Invoke the function with any integer 7 | print(tens_digit()) 8 | -------------------------------------------------------------------------------- /exercises/012-tens_digit/solution.hide.py: -------------------------------------------------------------------------------- 1 | # Complete the function to return the tens digit of a given integer 2 | def tens_digit(num): 3 | return (num // 10) % 10 4 | 5 | 6 | # Invoke the function with any integer 7 | print(tens_digit(198)) 8 | -------------------------------------------------------------------------------- /exercises/012-tens_digit/test.py: -------------------------------------------------------------------------------- 1 | import io, sys, pytest, os, re, mock 2 | 3 | @pytest.mark.it('The function tens_digit must exist') 4 | def test_for_functon_existence(capsys, app): 5 | assert callable(app.tens_digit) 6 | 7 | @pytest.mark.it('The function must return something') 8 | def test_for_return(capsys, app): 9 | assert app.tens_digit(123) != None 10 | 11 | @pytest.mark.it('The function must return a number') 12 | def test_for_output_type(capsys, app): 13 | assert type(app.tens_digit(123)) == type(1) 14 | 15 | @pytest.mark.it('We tried to pass 854345 as parameter and it did not return 4') 16 | def test_for_file_output(capsys, app): 17 | assert app.tens_digit(854345) == (854345 // 10)%10 18 | 19 | 20 | -------------------------------------------------------------------------------- /exercises/013-sum_of_digits/README.es.md: -------------------------------------------------------------------------------- 1 | # `013` sum of digits 2 | 3 | ## 📝 Instrucciones: 4 | 5 | 1. Completa la función `digits_sum()` para que dado un número de tres dígitos, retorne la suma de sus dígitos. 6 | 7 | ## 📎 Ejemplo de entrada: 8 | 9 | ```py 10 | digits_sum(123) 11 | ``` 12 | 13 | ## 📎 Ejemplo de salida: 14 | 15 | ```py 16 | 6 17 | ``` 18 | 19 | ## 💡 Pistas: 20 | 21 | + Si no sabes por donde comenzar este ejercicio, por favor, revisa la teoría en esta lección: https://snakify.org/lessons/integer_float_numbers/ 22 | 23 | + También puedes intentar paso a paso con trozos de la teoría: https://snakify.org/lessons/integer_float_numbers/steps/1/ 24 | -------------------------------------------------------------------------------- /exercises/013-sum_of_digits/README.md: -------------------------------------------------------------------------------- 1 | # `013` sum of digits 2 | 3 | ## 📝 Instructions: 4 | 5 | 1. Complete the `digits_sum()` function. Given a three-digit number, `digits_sum()` finds the sum of its digits. 6 | 7 | ## 📎 Example input: 8 | 9 | ```py 10 | digits_sum(123) 11 | ``` 12 | 13 | ## 📎 Example output: 14 | 15 | ```py 16 | 6 17 | ``` 18 | 19 | ## 💡 Hints: 20 | 21 | + If you don't know how to start solving this assignment, please review the theory for this lesson: https://snakify.org/lessons/integer_float_numbers/ 22 | 23 | + You may also try step-by-step theory chunks: https://snakify.org/lessons/integer_float_numbers/steps/1/ 24 | -------------------------------------------------------------------------------- /exercises/013-sum_of_digits/app.py: -------------------------------------------------------------------------------- 1 | # Complete the function "digits_sum" so that it prints the sum of a three-digit number 2 | def digits_sum(num): 3 | return None 4 | 5 | 6 | # Invoke the function with any three-digit number 7 | print(digits_sum(123)) 8 | -------------------------------------------------------------------------------- /exercises/013-sum_of_digits/solution.hide.py: -------------------------------------------------------------------------------- 1 | # Complete the function "digits_sum" so that it prints the sum of a three-digit number 2 | def digits_sum(num): 3 | aux = 0 4 | for x in str(num): 5 | aux = aux + int(x) 6 | return aux 7 | 8 | 9 | # Invoke the function with any three-digit number 10 | print(digits_sum(123)) 11 | -------------------------------------------------------------------------------- /exercises/013-sum_of_digits/test.py: -------------------------------------------------------------------------------- 1 | import io, sys, pytest, os, re, mock 2 | 3 | @pytest.mark.it('The function digits_sum must exist') 4 | def test_for_functon_existence(capsys, app): 5 | assert callable(app.digits_sum) 6 | 7 | @pytest.mark.it('The function must return something') 8 | def test_for_return(capsys, app): 9 | assert app.digits_sum(123) != None 10 | 11 | @pytest.mark.it('The function must return a number') 12 | def test_for_output_type(capsys, app): 13 | assert type(app.digits_sum(123)) == type(1) 14 | 15 | @pytest.mark.it('We tried to pass 854 as parameter and it did not return 17') 16 | def test_for_file_output(capsys, app): 17 | assert app.digits_sum(854) == (854 //100)+(854 // 10)%10+ 854%10 18 | 19 | 20 | 21 | 22 | 23 | 24 | -------------------------------------------------------------------------------- /exercises/014-digit_after_decimal_point/README.es.md: -------------------------------------------------------------------------------- 1 | # `014` digit after decimal point 2 | 3 | ## 📝 Instrucciones: 4 | 5 | 1. Completa la función `first_digit()` para que dado un número real positivo, devuelve su primer decimal (a la derecha del punto). 6 | 7 | ## 📎 Ejemplo de entrada: 8 | 9 | ```py 10 | first_digit(1.79) 11 | ``` 12 | 13 | ## 📎 Ejemplo de salida: 14 | 15 | ``` 16 | 7 17 | ``` 18 | 19 | ## 💡 Pistas: 20 | 21 | + Si no sabes por donde comenzar este ejercicio, por favor, revisa la teoría en esta lección: https://snakify.org/lessons/integer_float_numbers/ 22 | 23 | + También puedes intentar paso a paso con trozos de la teoría: https://snakify.org/lessons/integer_float_numbers/steps/1/ 24 | -------------------------------------------------------------------------------- /exercises/014-digit_after_decimal_point/README.md: -------------------------------------------------------------------------------- 1 | # `014` digit after decimal point 2 | 3 | ## 📝 Instructions: 4 | 5 | 1. Complete the `first_digit()` function. Given a positive real number, `first_digit()` returns its first digit (to the right of the decimal point). 6 | 7 | ## 📎 Example input: 8 | 9 | ```py 10 | first_digit(1.79) 11 | ``` 12 | 13 | ## 📎 Example output: 14 | 15 | ```py 16 | 7 17 | ``` 18 | 19 | ## 💡 Hints: 20 | 21 | + If you don't know how to start solving this assignment, please review the theory for this lesson: https://snakify.org/lessons/integer_float_numbers/ 22 | 23 | + You may also try step-by-step theory chunks: https://snakify.org/lessons/integer_float_numbers/steps/1/ 24 | -------------------------------------------------------------------------------- /exercises/014-digit_after_decimal_point/app.py: -------------------------------------------------------------------------------- 1 | # Complete the function to return the first digit to the right of the decimal point 2 | def first_digit(num): 3 | return None 4 | 5 | 6 | # Invoke the function with a positive real number. ex. 34.33 7 | print(first_digit()) 8 | -------------------------------------------------------------------------------- /exercises/014-digit_after_decimal_point/solution.hide.py: -------------------------------------------------------------------------------- 1 | import math 2 | 3 | # Complete the function to return the first digit to the right of the decimal point 4 | def first_digit(num): 5 | return int(str(math.floor(num*10)/10)[-1]) 6 | 7 | 8 | # Invoke the function with a positive real number. ex. 34.33 9 | print(first_digit(2.6)) 10 | -------------------------------------------------------------------------------- /exercises/014-digit_after_decimal_point/test.py: -------------------------------------------------------------------------------- 1 | import io, sys, pytest, os, re, mock 2 | 3 | @pytest.mark.it('The function first_digit must exist') 4 | def test_for_functon_existence(capsys, app): 5 | assert callable(app.first_digit) 6 | 7 | @pytest.mark.it('The function must return something') 8 | def test_for_return(capsys, app): 9 | assert app.first_digit(1.2) != None 10 | 11 | @pytest.mark.it('The function must return a number') 12 | def test_for_output_type(capsys, app): 13 | assert type(app.first_digit(1.2)) == type(1) 14 | 15 | @pytest.mark.it('We tried to pass 6.24 as parameter and it did not return 2') 16 | def test_for_file_output(capsys, app): 17 | assert app.first_digit(6.24) == int(6.24 *10)%10 18 | 19 | -------------------------------------------------------------------------------- /exercises/015-car_route/README.es.md: -------------------------------------------------------------------------------- 1 | # `015` car route 2 | 3 | Un vehículo puede cubrir una distancia de `N` kilómetros por día ¿Cuántos días le tomará cubrir una ruta de `M` kilómetros de longitud? 4 | 5 | ## 📝 Instrucciones: 6 | 7 | 1. Escribe una función `car_route()` que dada la distancia que puede recorrer en un día como primer parámetro, y como segundo parámetro la distancia a recorrer, calcule la cantidad de días que le tomara recorrer dicha distancia. 8 | 9 | ## 📎 Ejemplo de entrada: 10 | 11 | ```py 12 | car_route(20, 40) 13 | ``` 14 | 15 | ## 📎 Ejemplo de salida: 16 | 17 | ```py 18 | 2 19 | ``` 20 | 21 | ## 💡 Pistas: 22 | 23 | + El programa recibe dos números: `N` y `M`. 24 | 25 | + Debes redondear el resultado hacia arriba si obtienes un decimal, es decir, si te toma 1.1 días recorrer la distancia, debe retornar 2. 26 | 27 | + Sería buena idea que importaras el módulo `math` para este ejercicio. 28 | 29 | + Si no sabes por donde comenzar este ejercicio, por favor, revisa la teoría en esta lección: https://snakify.org/lessons/integer_float_numbers/ 30 | 31 | + También puedes intentar paso a paso con trozos de la teoría: https://snakify.org/lessons/integer_float_numbers/steps/1/ 32 | -------------------------------------------------------------------------------- /exercises/015-car_route/README.md: -------------------------------------------------------------------------------- 1 | # `015` car route 2 | 3 | A car can cover a distance of `N` kilometers per day. How many days will it take to cover a route of length `M` kilometers? 4 | 5 | ## 📝 Instructions: 6 | 7 | 1. Write a `car_route()` function that, given the distance it can drive in one day as the first parameter, and the distance to drive as the second parameter, calculates the number of days it will take to drive that distance. 8 | 9 | ## 📎 Example input: 10 | 11 | ```py 12 | car_route(20, 40) 13 | ``` 14 | 15 | ## 📎 Example output: 16 | 17 | ```py 18 | 2 19 | ``` 20 | 21 | ## 💡 Hints: 22 | 23 | + The program gets two numbers: `N` and `M`. 24 | 25 | + You must round up the outcome if you get a float, for example, if it takes you 1.1 days to travel the distance, it must return 2. 26 | 27 | + You may need to import the `math` module for this exercise. 28 | 29 | + If you don't know how to start solving this assignment, please review the theory for this lesson: https://snakify.org/lessons/integer_float_numbers/ 30 | 31 | + You may also try step-by-step theory chunks: https://snakify.org/lessons/integer_float_numbers/steps/1/ 32 | -------------------------------------------------------------------------------- /exercises/015-car_route/app.py: -------------------------------------------------------------------------------- 1 | # Complete the function to return the amount of days it will take to cover a route 2 | def car_route(n,m): 3 | return None 4 | 5 | 6 | # Invoke the function with two integers 7 | print(car_route()) 8 | -------------------------------------------------------------------------------- /exercises/015-car_route/solution.hide.py: -------------------------------------------------------------------------------- 1 | import math 2 | 3 | # Complete the function to return the amount of days it will take to cover a route 4 | def car_route(n,m): 5 | return int(math.ceil(m/n)) 6 | 7 | 8 | # Invoke the function with two integers 9 | print(car_route(35, 50)) 10 | -------------------------------------------------------------------------------- /exercises/015-car_route/test.py: -------------------------------------------------------------------------------- 1 | import io, sys, pytest, os, re, mock, math 2 | path = os.path.dirname(os.path.abspath(__file__))+'/app.py' 3 | 4 | @pytest.mark.it("You need to import the math module") 5 | def test_import_random(): 6 | with open(path, 'r') as content_file: 7 | content = content_file.read() 8 | regex = re.compile(r"import(\s)+math") 9 | assert bool(regex.search(content)) == True 10 | 11 | @pytest.mark.it('The function car_route must exist') 12 | def test_for_functon_existence(capsys, app): 13 | assert callable(app.car_route) 14 | 15 | @pytest.mark.it('The function must return something') 16 | def test_function_return(capsys, app): 17 | assert app.car_route(659, 1857) != None 18 | 19 | @pytest.mark.it('The function must return a number') 20 | def test_function_return_type(capsys, app): 21 | assert type(app.car_route(659, 1857)) == type(1) 22 | 23 | @pytest.mark.it('We tried to pass 20 and 40 as parameter and it did not return 2') 24 | def test_for_file_output(capsys, app): 25 | assert app.car_route(20, 40) == 2 26 | 27 | @pytest.mark.it('We tried to pass 20 and 900 as parameter and it did not return 45') 28 | def test_for_file_output2(capsys, app): 29 | assert app.car_route(20, 900) == 45 30 | 31 | 32 | 33 | 34 | 35 | 36 | -------------------------------------------------------------------------------- /exercises/016-century/README.es.md: -------------------------------------------------------------------------------- 1 | # `016` century 2 | 3 | ## 📝 Instrucciones: 4 | 5 | 1. Escribe una función `century()` para que dado un año (como un entero positivo), encuentre su posición respectiva dentro del siglo. 6 | 7 | ## 📎 Ejemplo de entrada: 8 | 9 | ```py 10 | century(2001) 11 | ``` 12 | 13 | ## 📎 Ejemplo de salida: 14 | 15 | ```py 16 | 21 17 | ``` 18 | 19 | ## 💡 Pistas: 20 | 21 | + Ten en cuenta que, por ejemplo, el s. XX (siglo 20) comienza en el año 1901. 22 | 23 | + Sería buena idea que importaras el módulo `math` para este ejercicio. 24 | 25 | + Si no sabes por donde comenzar este ejercicio, por favor, revisa la teoría en esta lección: 26 | https://snakify.org/lessons/integer_float_numbers/ 27 | 28 | + También puedes intentar paso a paso con trozos de la teoría: 29 | https://snakify.org/lessons/integer_float_numbers/steps/1/ 30 | -------------------------------------------------------------------------------- /exercises/016-century/README.md: -------------------------------------------------------------------------------- 1 | # `016` century 2 | 3 | ## 📝 Instructions: 4 | 5 | 1. Write a function `century()`. Given a year (as a positive integer), `century()` finds the respective number of the century. 6 | 7 | ## 📎 Example input: 8 | 9 | ```py 10 | century(2001) 11 | ``` 12 | 13 | ## 📎 Example output: 14 | 15 | ```py 16 | 21 17 | ``` 18 | 19 | ## 💡 Hints: 20 | 21 | + Note that, for example, the 20th century began with the year 1901. 22 | 23 | + You may need to import the `math` module. 24 | 25 | + If you don't know how to start solving this assignment, please review the theory for this lesson: https://snakify.org/lessons/integer_float_numbers/ 26 | 27 | + You may also try step-by-step theory chunks: https://snakify.org/lessons/integer_float_numbers/steps/1/ 28 | -------------------------------------------------------------------------------- /exercises/016-century/app.py: -------------------------------------------------------------------------------- 1 | # Complete the function to return the respective number of the century 2 | def century(year): 3 | return None 4 | 5 | 6 | # Invoke the function with any given year 7 | print(century()) 8 | -------------------------------------------------------------------------------- /exercises/016-century/solution.hide.py: -------------------------------------------------------------------------------- 1 | import math 2 | 3 | # Complete the function to return the respective number of the century 4 | def century(year): 5 | if year % 100 == 0: 6 | return math.floor(year / 100) 7 | else: 8 | return math.floor(year / 100 + 1) 9 | 10 | 11 | # Invoke the function with any given year 12 | print(century(2024)) 13 | -------------------------------------------------------------------------------- /exercises/016-century/test.py: -------------------------------------------------------------------------------- 1 | import io, sys, pytest, os, re, mock, math 2 | path = os.path.dirname(os.path.abspath(__file__))+'/app.py' 3 | 4 | @pytest.mark.it("You need to import the math module") 5 | def test_import_random(): 6 | with open(path, 'r') as content_file: 7 | content = content_file.read() 8 | regex = re.compile(r"import(\s)+math") 9 | assert bool(regex.search(content)) == True 10 | 11 | 12 | @pytest.mark.it('The function century must exist') 13 | def test_for_functon_existence(capsys, app): 14 | assert callable(app.century) 15 | 16 | @pytest.mark.it('The function must return something') 17 | def test_function_return(capsys, app): 18 | assert app.century(19001) != None 19 | 20 | @pytest.mark.it('The function must return a number') 21 | def test_function_return_type(capsys, app): 22 | assert type(app.century(19001)) == type(1) 23 | 24 | @pytest.mark.it('We tried to pass 2000 as parameter and it did not return 20') 25 | def test_for_file_output(capsys, app): 26 | assert app.century(2000) == 20 27 | 28 | @pytest.mark.it('We tried to pass 2001 as parameter and it did not return 21') 29 | def test_for_file_output2(capsys, app): 30 | assert app.century(2001) == 21 31 | 32 | @pytest.mark.it('We tried to pass 2101 as parameter and it did not return 22') 33 | def test_for_file_output3(capsys, app): 34 | assert app.century(2101) == 22 35 | 36 | -------------------------------------------------------------------------------- /exercises/017-total_cost/README.es.md: -------------------------------------------------------------------------------- 1 | # `017` total cost 2 | 3 | ## 📝 Instrucciones: 4 | 5 | 1. Un cupcake cuesta `d` dólares y `c` centavos. Escribe una función `total_cost()` para determinar cuántos dólares y centavos debería pagar una persona por `n` cupcakes. *La función recibe tres números: `d`, `c`, `n` y debería devolver dos números: costo total en dólares y centavos* 6 | 7 | ## 📎 Ejemplo de entrada: 8 | 9 | ```py 10 | total_cost(10,15,2) 11 | ``` 12 | 13 | ## 📎 Ejemplo de salida: 14 | 15 | ```py 16 | (20, 30) 17 | ``` 18 | 19 | ## 💡 Pistas: 20 | 21 | + Si no sabes por donde comenzar este ejercicio, por favor, revisa la teoría en esta lección: https://snakify.org/lessons/integer_float_numbers/ 22 | 23 | + También puedes intentar paso a paso con trozos de la teoría: https://snakify.org/lessons/integer_float_numbers/steps/1/ 24 | -------------------------------------------------------------------------------- /exercises/017-total_cost/README.md: -------------------------------------------------------------------------------- 1 | # `017` total cost 2 | 3 | ## 📝 Instructions: 4 | 5 | 1. A cupcake costs `d` dollars and `c` cents. Write a function that determines how many dollars and cents someone should pay for `n` cupcakes. *The function gets three numbers: `d`, `c`, `n` and it should return two numbers: total cost in dollars and cents.* 6 | 7 | ## 📎 Example input: 8 | 9 | ```py 10 | total_cost(10,15,2) 11 | ``` 12 | 13 | ## 📎 Example output: 14 | 15 | ```py 16 | (20, 30) 17 | ``` 18 | 19 | ## 💡 Hints: 20 | 21 | + If you don't know how to start solving this assignment, please review the theory for this lesson: https://snakify.org/lessons/integer_float_numbers/ 22 | 23 | + You may also try step-by-step theory chunks: https://snakify.org/lessons/integer_float_numbers/steps/1/ 24 | -------------------------------------------------------------------------------- /exercises/017-total_cost/app.py: -------------------------------------------------------------------------------- 1 | # Complete the function to return the total cost in dollars and cents of (n) cupcakes 2 | def total_cost(d, c, n): 3 | return None 4 | 5 | 6 | # Invoke the function with three integers: total_cost(dollars, cents, number_of_cupcakes) 7 | print(total_cost(15,22,4)) 8 | -------------------------------------------------------------------------------- /exercises/017-total_cost/solution.hide.py: -------------------------------------------------------------------------------- 1 | # Complete the function to return the total cost in dollars and cents of (n) cupcakes 2 | def total_cost(d, c, n): 3 | total_cents = (d * 100 + c) * n 4 | total_dollars = total_cents // 100 5 | remaining_cents = total_cents % 100 6 | return total_dollars, remaining_cents 7 | 8 | 9 | # Invoke the function with three integers: total_cost(dollars, cents, number_of_cupcakes) 10 | print(total_cost(15,22,4)) 11 | -------------------------------------------------------------------------------- /exercises/017-total_cost/test.py: -------------------------------------------------------------------------------- 1 | import io, sys, pytest, os, re, mock, math 2 | path = os.path.dirname(os.path.abspath(__file__))+'/app.py' 3 | 4 | 5 | @pytest.mark.it('The function total_cost must exist') 6 | def test_for_functon_existence(capsys, app): 7 | assert callable(app.total_cost) 8 | 9 | @pytest.mark.it('The function must return something') 10 | def test_function_return(capsys, app): 11 | assert app.total_cost(15, 22, 4) != None 12 | 13 | @pytest.mark.it('The function must return a tuple') 14 | def test_function_return_type(capsys, app): 15 | assert type(app.total_cost(15, 22, 4)) == type((60, 88)) 16 | 17 | @pytest.mark.it('The function must return a tuple of numbers') 18 | def test_function_return_type_parameters(capsys, app): 19 | result = app.total_cost(15, 22, 4) 20 | assert type(result[0]) == type(1) and type(result[1]) == type(1) 21 | 22 | @pytest.mark.it('We tried to pass 15, 22, 4 as parameters and it did not return (60, 88)') 23 | def test_for_file_output(capsys, app): 24 | assert app.total_cost(15, 22, 4) == (60, 88) 25 | 26 | @pytest.mark.it('We tried to pass 10, 15, 4 as parameters and it did not return (40, 60)') 27 | def test_for_file_output2(capsys, app): 28 | assert app.total_cost(10, 15, 4) == (40, 60) 29 | 30 | -------------------------------------------------------------------------------- /exercises/018-day_of_week/README.es.md: -------------------------------------------------------------------------------- 1 | # `018` day of week 2 | 3 | ## 📝 Instrucciones: 4 | 5 | 1. Escribe una función `day_of_week()`. Dado un entero `k` en el rango comprendido entre 1 a 365, `day_of_week()` encuentra el número del día de la semana para el k-ésimo día del año si este año el 1 de enero fue jueves. 6 | 7 | *Los días de la semana se enumeran así:* 8 | 9 | ```text 10 | 0 — Domingo 11 | 1 — Lunes 12 | 2 — Martes, ... 13 | 6 — Sábado 14 | ``` 15 | 16 | ## 📎 Ejemplo de entrada: 17 | 18 | ```py 19 | day_of_week(1) 20 | ``` 21 | 22 | ## 📎 Ejemplo de salida: 23 | 24 | ```py 25 | 4 26 | ``` 27 | 28 | ## 💡 Pistas: 29 | 30 | + Si no sabes por donde comenzar este ejercicio, por favor, revisa la teoría en esta lección: https://snakify.org/lessons/integer_float_numbers/ 31 | 32 | + También puedes intentar paso a paso con trozos de la teoría: https://snakify.org/lessons/integer_float_numbers/steps/1/ 33 | -------------------------------------------------------------------------------- /exercises/018-day_of_week/README.md: -------------------------------------------------------------------------------- 1 | # `018` day of week 2 | 3 | ## 📝 Instructions: 4 | 5 | 1. Write a function `day_of_week()`. Given an integer `k` in the range 1 to 365, `day_of_week()` finds the number of day of week for *k-th* day of the year, provided that in this year January 1 was Thursday. 6 | 7 | *The days of the week are numbered as:* 8 | 9 | ```text 10 | 0 — Sunday 11 | 1 — Monday 12 | 2 — Tuesday, ... 13 | 6 — Saturday 14 | ``` 15 | 16 | ## 📎 Example input: 17 | 18 | ```py 19 | day_of_week(1) 20 | ``` 21 | 22 | ## 📎 Example output: 23 | 24 | ```py 25 | 4 26 | ``` 27 | 28 | ## 💡 Hints: 29 | 30 | + If you don't know how to start solving this assignment, please review the theory for this lesson: https://snakify.org/lessons/integer_float_numbers/ 31 | 32 | + You may also try step-by-step theory chunks: https://snakify.org/lessons/integer_float_numbers/steps/1/ 33 | -------------------------------------------------------------------------------- /exercises/018-day_of_week/app.py: -------------------------------------------------------------------------------- 1 | # Complete the function to return the number of day of the week for k'th day of year 2 | def day_of_week(k): 3 | return None 4 | 5 | 6 | # Invoke function day_of_week with an integer between 1 and 365 7 | print(day_of_week()) 8 | -------------------------------------------------------------------------------- /exercises/018-day_of_week/solution.hide.py: -------------------------------------------------------------------------------- 1 | # Complete the function to return the number of day of the week for k'th day of year 2 | def day_of_week(k): 3 | return (3 + k) % 7 4 | 5 | 6 | # Invoke function day_of_week with an integer between 1 and 365 7 | print(day_of_week(125)) 8 | -------------------------------------------------------------------------------- /exercises/018-day_of_week/test.py: -------------------------------------------------------------------------------- 1 | import io, sys, pytest, os, re, mock, math 2 | path = os.path.dirname(os.path.abspath(__file__))+'/app.py' 3 | 4 | 5 | @pytest.mark.it('The function day_of_week must exist') 6 | def test_for_functon_existence(capsys, app): 7 | assert callable(app.day_of_week) 8 | 9 | @pytest.mark.it('The function must return something') 10 | def test_function_return(capsys, app): 11 | assert app.day_of_week(1) != None 12 | 13 | @pytest.mark.it('The function must return a number') 14 | def test_function_return_type(capsys, app): 15 | assert type(app.day_of_week(1)) == type(1) 16 | 17 | @pytest.mark.it('Something went wrong! We tried to pass 1 as parameter and it did not return 4. Keep trying!') 18 | def test_for_file_output(capsys, app): 19 | assert app.day_of_week(1) == 4 20 | 21 | @pytest.mark.it('Something went wrong! We tried to pass 46 as parameter and it did not return 0. Keep trying!') 22 | def test_for_file_output2(capsys, app): 23 | assert app.day_of_week(46) == 0 24 | 25 | -------------------------------------------------------------------------------- /exercises/019-digital_clock/README.es.md: -------------------------------------------------------------------------------- 1 | # `019` digital clock 2 | 3 | ## 📝 Instrucciones: 4 | 5 | 1. Dado un entero `n` que representa el número de minutos que han pasado desde media noche, ¿cuántas horas y minutos se mostrarían en un reloj digital con formato 24 horas? Escribe una función `digital_clock()` para calcularlo. *La función debería imprimir dos números: el número de horas (entre 0 y 23) y el número de minutos (entre 0 y 59).* 6 | 7 | ## 📎 Ejemplo de entrada: 8 | 9 | ```py 10 | digital_clock(150) 11 | ``` 12 | 13 | ## 📎 Ejemplo de salida: 14 | 15 | ```py 16 | (2, 30) 17 | ``` 18 | 19 | Por ejemplo, si n = 150, entonces son 150 minutos que han pasado desde medianoche. Es decir, ahora son las 2:30 am, así que la función debería imprimir (2, 30). 20 | 21 | ## 💡 Pistas: 22 | 23 | + Si no sabes por donde comenzar este ejercicio, por favor, revisa la teoría en esta lección: https://snakify.org/lessons/integer_float_numbers/ 24 | 25 | + También puedes intentar paso a paso con trozos de la teoría: https://snakify.org/lessons/integer_float_numbers/steps/1/ 26 | -------------------------------------------------------------------------------- /exercises/019-digital_clock/README.md: -------------------------------------------------------------------------------- 1 | # `019` digital clock 2 | 3 | ## 📝 Instructions: 4 | 5 | 1. Given the integer `n` - the number of minutes that have passed since midnight, how many hours and minutes are displayed on the 24h digital clock? Write a `digital_clock()` function to calculate it. *The function should print two numbers: the number of hours (between 0 and 23) and the number of minutes (between 0 and 59).* 6 | 7 | ## 📎 Example input: 8 | 9 | ```py 10 | digital_clock(150) 11 | ``` 12 | 13 | ## 📎 Example output: 14 | 15 | ```py 16 | (2, 30) 17 | ``` 18 | 19 | For example, if n = 150, then 150 minutes have passed since midnight - i.e. now is 2:30 am. So the function should print (2, 30). 20 | 21 | ## 💡 Hints: 22 | 23 | + If you don't know how to start solving this assignment, please review the theory for this lesson: https://snakify.org/lessons/integer_float_numbers/ 24 | 25 | + You may also try step-by-step theory chunks: https://snakify.org/lessons/integer_float_numbers/steps/1/ 26 | -------------------------------------------------------------------------------- /exercises/019-digital_clock/app.py: -------------------------------------------------------------------------------- 1 | # Complete the function to return how many hours and minutes are displayed on the 24h digital clock 2 | def digital_clock(n): 3 | return None 4 | 5 | # Invoke the function with any integer (minutes after midnight) 6 | print(digital_clock()) 7 | -------------------------------------------------------------------------------- /exercises/019-digital_clock/solution.hide.py: -------------------------------------------------------------------------------- 1 | # Complete the function to return how many hours and minutes are displayed on the 24h digital clock 2 | def digital_clock(n): 3 | return ((n // 60), (n % 60)) 4 | 5 | # Invoke the function with any integer (minutes after midnight) 6 | print(digital_clock(150)) 7 | -------------------------------------------------------------------------------- /exercises/019-digital_clock/test.py: -------------------------------------------------------------------------------- 1 | import io, sys, pytest, os, re, mock, math 2 | path = os.path.dirname(os.path.abspath(__file__))+'/app.py' 3 | 4 | 5 | @pytest.mark.it('The function digital_clock must exist') 6 | def test_for_functon_existence(capsys, app): 7 | assert callable(app.digital_clock) 8 | 9 | @pytest.mark.it('The function must return something') 10 | def test_function_return(capsys, app): 11 | assert app.digital_clock(194) != None 12 | 13 | @pytest.mark.it('The function must return a tuple') 14 | def test_function_return_type(capsys, app): 15 | assert type(app.digital_clock(194)) == type((3, 14)) 16 | 17 | @pytest.mark.it('We tried to pass 194 as parameter and it did not return (3, 14). Keep Trying!') 18 | def test_for_file_output(capsys, app): 19 | assert app.digital_clock(194) == (3, 14) 20 | 21 | @pytest.mark.it('We tried to pass 150 as parameter and it did not return (2, 30). Keep Trying!') 22 | def test_for_file_output(capsys, app): 23 | assert app.digital_clock(150) == (2, 30) 24 | 25 | -------------------------------------------------------------------------------- /exercises/020-factorial/README.es.md: -------------------------------------------------------------------------------- 1 | # `020` factorial 2 | 3 | ## 📝 Instrucciones: 4 | 5 | 1. Crea una función llamada `factorial()`, que al recibir un número como parámetro retorne su valor factorial. 6 | 7 | ## 📎 Ejemplo de entrada: 8 | 9 | ```py 10 | factorial(8) 11 | ``` 12 | 13 | ## 📎 Ejemplo de salida: 14 | 15 | ```py 16 | 40320 17 | ``` 18 | 19 | ## 💡 Pista: 20 | 21 | + Si no sabes qué es un factorial, revisa la información de este link: https://factorial.mx/numero-funcion-factorial 22 | -------------------------------------------------------------------------------- /exercises/020-factorial/README.md: -------------------------------------------------------------------------------- 1 | # `020` factorial 2 | 3 | ## 📝 Instructions: 4 | 5 | 1. Create a function named `factorial()`, which receives a number as a parameter and returns the factorial of the given number. 6 | 7 | ## 📎 Example input: 8 | 9 | ```py 10 | factorial(8) 11 | ``` 12 | 13 | ## 📎 Example output: 14 | 15 | ```py 16 | 40320 17 | ``` 18 | 19 | ## 💡 Hint: 20 | 21 | + If you don't know what a factorial is, you can check it out on this link: https://www.cuemath.com/numbers/factorial/ 22 | -------------------------------------------------------------------------------- /exercises/020-factorial/app.py: -------------------------------------------------------------------------------- 1 | # Your code here 2 | -------------------------------------------------------------------------------- /exercises/020-factorial/solution.hide.py: -------------------------------------------------------------------------------- 1 | # Your code here 2 | def factorial(x): 3 | result = 1 4 | for i in range(1, x + 1): 5 | result *= i 6 | return result 7 | 8 | print(factorial(5)) 9 | 10 | ### Solution 2 ### 11 | 12 | # import math 13 | # 14 | # def factorial(x): 15 | # return math.factorial(x) 16 | # 17 | # print(factorial(8)) 18 | -------------------------------------------------------------------------------- /exercises/020-factorial/test.py: -------------------------------------------------------------------------------- 1 | import io, sys, os, re, pytest 2 | import app 3 | 4 | @pytest.mark.it('You should create a function named factorial') 5 | def test_factorial_exists(app): 6 | try: 7 | from app import factorial 8 | assert factorial 9 | except AttributeError: 10 | raise AttributeError("The function 'factorial' should exist on app.py") 11 | 12 | @pytest.mark.it('The function must return something') 13 | def test_function_return(capsys, app): 14 | assert app.factorial(8) != None 15 | 16 | @pytest.mark.it('The function must return a number') 17 | def test_function_return_type(capsys, app): 18 | assert type(app.factorial(8)) == type(1) 19 | 20 | @pytest.mark.it('Testing the function factorial with the number 8, it should return 40320') 21 | def test_factorial_8(app): 22 | try: 23 | assert app.factorial(8) == 40320 24 | except AttributeError: 25 | raise AttributeError("The function 'factorial' should return the value 40320") 26 | 27 | @pytest.mark.it('Testing the function factorial with the number 3, it should return 6') 28 | def test_factorial_3(app): 29 | try: 30 | assert app.factorial(3) == 6 31 | except AttributeError: 32 | raise AttributeError("The function 'factorial' should return the value 6") 33 | 34 | @pytest.mark.it('Testing the function factorial with the number 1, it should return 1') 35 | def test_factorial_1(app): 36 | try: 37 | assert app.factorial(1) == 1 38 | except AttributeError: 39 | raise AttributeError("The function 'factorial' should return the value 1") 40 | 41 | -------------------------------------------------------------------------------- /exercises/021-square_root/README.es.md: -------------------------------------------------------------------------------- 1 | # `021` square root 2 | 3 | ## 📝 Instrucciones: 4 | 5 | 1. Crea una función llamada `square_root()`, que reciba un número como parámetro y devuelva la raíz cuadrada del número dado. 6 | 7 | 2. Si el número resultante tiene decimales, solo conserva los 2 primeros. 8 | 9 | ## 📎 Ejemplo de entrada: 10 | 11 | ```py 12 | square_root(50) 13 | ``` 14 | 15 | ## 📎 Ejemplo de salida: 16 | 17 | ```py 18 | 7.07 19 | ``` 20 | 21 | ## 💡 Pistas: 22 | 23 | + Recuerda que el módulo `math` es una herramienta muy útil. 24 | 25 | + Para conservar el número deseado de decimales en un número dado, puedes utilizar el método `round()`. 26 | -------------------------------------------------------------------------------- /exercises/021-square_root/README.md: -------------------------------------------------------------------------------- 1 | # `021` square root 2 | 3 | ## 📝 Instructions: 4 | 5 | 1. Create a function named `square_root()`, which receives a number as a parameter and returns the square root of the given number. 6 | 7 | 2. If the resulting number has decimals, please only keep the first 2. 8 | 9 | ## 📎 Example input: 10 | 11 | ```py 12 | square_root(50) 13 | ``` 14 | 15 | ## 📎 Example output: 16 | 17 | ```py 18 | 7.07 19 | ``` 20 | 21 | ## 💡 Hints: 22 | 23 | + Remember, the `math` module is a very useful tool. 24 | 25 | + To keep the desired number of decimals in a given number, you can use the `round()` method. 26 | -------------------------------------------------------------------------------- /exercises/021-square_root/app.py: -------------------------------------------------------------------------------- 1 | # Your code here 2 | -------------------------------------------------------------------------------- /exercises/021-square_root/solution.hide.py: -------------------------------------------------------------------------------- 1 | # Your code here 2 | import math 3 | 4 | def square_root(number): 5 | result = round(math.sqrt(number), 2) 6 | return result 7 | 8 | 9 | print(square_root(50)) -------------------------------------------------------------------------------- /exercises/021-square_root/test.py: -------------------------------------------------------------------------------- 1 | import io, sys, os, re, pytest 2 | import app 3 | 4 | @pytest.mark.it('You should create a function named square_root') 5 | def test_square_root_exists(app): 6 | try: 7 | from app import square_root 8 | assert square_root 9 | except AttributeError: 10 | raise AttributeError("The function 'square_root' should exist on app.py") 11 | 12 | @pytest.mark.it('The function must return something') 13 | def test_function_return(capsys, app): 14 | assert app.square_root(25) != None 15 | 16 | @pytest.mark.it('The function must return a float number') 17 | def test_function_return_type(capsys, app): 18 | assert type(app.square_root(25)) == type(1.0) 19 | 20 | @pytest.mark.it('Testing the function square_root with the number 50, it should return 7.07') 21 | def test_square_root_50(app): 22 | try: 23 | assert app.square_root(50) == 7.07 24 | except AttributeError: 25 | raise AttributeError("The function 'square_root' should return the value 7.07") 26 | 27 | @pytest.mark.it('Testing the function square_root with the number 2.25, it should return 1.5') 28 | def test_square_root_2_25(app): 29 | try: 30 | assert app.square_root(2.25) == 1.5 31 | except AttributeError: 32 | raise AttributeError("The function 'square_root' should return the value 1.5") 33 | 34 | @pytest.mark.it('Testing the function square_root with the number 0, it should return 0') 35 | def test_square_root_0(app): 36 | try: 37 | assert app.square_root(0) == 0 38 | except AttributeError: 39 | raise AttributeError("The function 'square_root' should return the value 0") -------------------------------------------------------------------------------- /exercises/022-Integral/README.es.md: -------------------------------------------------------------------------------- 1 | # `022` Integral 2 | 3 | ## 📝 Instrucciones: 4 | 5 | 1. Crea una función llamada `squares_dictionary()`. La función recibe un número `n` y debería generar un diccionario que contenga pares de la forma `(n: n*n)` para cada número en el rango de 1 a n, inclusive. 6 | 7 | 2. Imprime el diccionario resultante. 8 | 9 | ## 📎 Ejemplo de entrada: 10 | 11 | ```py 12 | squares_dictionary(8) 13 | ``` 14 | 15 | ## 📎 Ejemplo de salida: 16 | 17 | ```py 18 | {1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64} 19 | ``` 20 | 21 | ## 💡 Pista: 22 | 23 | + Un bucle `for` sería buena idea. 24 | -------------------------------------------------------------------------------- /exercises/022-Integral/README.md: -------------------------------------------------------------------------------- 1 | # `022` Integral 2 | 3 | ## 📝 Instructions: 4 | 5 | 1. Create a function called `squares_dictionary()`. The function receives a number `n` and should generate a dictionary that contains pairs of the form `(n: n*n)` for each number in the range from 1 to n, inclusive. 6 | 7 | 2. Print the resulting dictionary. 8 | 9 | ## 📎 Example input: 10 | 11 | ```py 12 | squares_dictionary(8) 13 | ``` 14 | 15 | ## 📎 Example output: 16 | 17 | ```py 18 | {1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64} 19 | ``` 20 | 21 | ## 💡 Hint: 22 | 23 | + A `for` loop would be a good idea. 24 | -------------------------------------------------------------------------------- /exercises/022-Integral/app.py: -------------------------------------------------------------------------------- 1 | # Your code here 2 | -------------------------------------------------------------------------------- /exercises/022-Integral/solution.hide.py: -------------------------------------------------------------------------------- 1 | # Your code here 2 | def squares_dictionary(n): 3 | new_dict = dict() 4 | for i in range(1, n + 1): 5 | new_dict[i] = i * i 6 | return new_dict 7 | 8 | print(squares_dictionary(5)) 9 | -------------------------------------------------------------------------------- /exercises/022-Integral/test.py: -------------------------------------------------------------------------------- 1 | import pytest,os,re,io,sys, mock, json 2 | 3 | @pytest.mark.it('The function squares_dictionary should exist') 4 | def test_function_existence(capsys, app): 5 | assert app.squares_dictionary 6 | 7 | @pytest.mark.it('The function should return a dictionary') 8 | def test_typeof_return(capsys, app): 9 | assert type(app.squares_dictionary(7)) == type({}) 10 | 11 | @pytest.mark.it('The function should return the expected output. Testing with 8') 12 | def test_expected_output(capsys, app): 13 | assert app.squares_dictionary(8) == {1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64} 14 | 15 | @pytest.mark.it('The function should return the expected output. Testing with 5') 16 | def test_another_entry_5(capsys, app): 17 | assert app.squares_dictionary(5) == {1: 1, 2: 4, 3: 9, 4: 16, 5: 25} 18 | 19 | -------------------------------------------------------------------------------- /exercises/023-list-and-tuple/README.es.md: -------------------------------------------------------------------------------- 1 | # `023` List and tuple 2 | 3 | ## 📝 Instrucciones: 4 | 5 | 1. Crea una función llamada `list_and_tuple()` que, dado un conjunto de `n` números como entrada, devuelve una lista y una tupla con esos números y los transforma a cada uno de ellos en string. 6 | 7 | 2. Imprime la lista primero, y en la siguiente línea la tupla. 8 | 9 | ## 📎 Ejemplo de entrada: 10 | 11 | ```py 12 | list_and_tuple(34,67,55,33,12,98) 13 | ``` 14 | 15 | ## 📎 Ejemplo de salida: 16 | 17 | ```py 18 | ['34', '67', '55', '33', '12', '98'] 19 | ('34', '67', '55', '33', '12', '98') 20 | ``` 21 | 22 | ## 💡 Pistas: 23 | 24 | + La cantidad de parámetros aceptados por la función no está limitado. 25 | 26 | + Para crear una función que acepta un número ilimitado de argumentos, utiliza el operador `*` y luego cualquier nombre que desees. De esta forma: 27 | 28 | ```py 29 | def my_function(*args) 30 | ``` 31 | -------------------------------------------------------------------------------- /exercises/023-list-and-tuple/README.md: -------------------------------------------------------------------------------- 1 | # `023` List and tuple 2 | 3 | ## 📝 Instructions: 4 | 5 | 1. Create a function called `list_and_tuple()`, that given a input of `n` numbers returns a list and a tuple of those numbers and transforms each of them into a string. 6 | 7 | 2. Print the list, and in the next line, print the tuple. 8 | 9 | ## 📎 Example input: 10 | 11 | ```py 12 | list_and_tuple(34,67,55,33,12,98) 13 | ``` 14 | 15 | ## 📎 Example output: 16 | 17 | ```py 18 | ['34', '67', '55', '33', '12', '98'] 19 | ('34', '67', '55', '33', '12', '98') 20 | ``` 21 | 22 | ## 💡 Hints: 23 | 24 | + The number of parameters accepted by the function is not limited. 25 | 26 | + To make a function that accepts an unlimited number of arguments, use the `*` operator and then any name you want for it. For example: 27 | 28 | ```py 29 | def my_function(*args) 30 | ``` 31 | -------------------------------------------------------------------------------- /exercises/023-list-and-tuple/app.py: -------------------------------------------------------------------------------- 1 | # Your code here 2 | -------------------------------------------------------------------------------- /exercises/023-list-and-tuple/solution.hide.py: -------------------------------------------------------------------------------- 1 | # Your code here 2 | def list_and_tuple(*nums): 3 | new_list = [str(num) for num in nums] 4 | new_tuple = tuple(new_list) 5 | 6 | return new_list, new_tuple 7 | 8 | 9 | result_list, result_tuple = list_and_tuple(5, 4, 13, 24, 45) 10 | print(result_list) 11 | print(result_tuple) 12 | -------------------------------------------------------------------------------- /exercises/023-list-and-tuple/test.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | 3 | @pytest.mark.it('You should create a function named "list_and_tuple"') 4 | def test_variable_exists(app): 5 | try: 6 | assert app.list_and_tuple 7 | except AttributeError: 8 | raise AttributeError('The function "list_and_tuple" should exists') 9 | 10 | @pytest.mark.it('The function "list_and_tuple" should return two elements') 11 | def test_function_return_two_elements(app): 12 | try: 13 | value = app.list_and_tuple() 14 | assert isinstance(value, tuple) 15 | assert len(value) == 2 16 | except AttributeError: 17 | raise AttributeError('The function "list_and_tuple" should exists') 18 | 19 | @pytest.mark.it('The function "list_and_tuple" should return a list first') 20 | def test_function_return_a_list(app): 21 | try: 22 | value = app.list_and_tuple() 23 | assert isinstance(value, tuple) 24 | assert isinstance(value[0], list) 25 | except AttributeError: 26 | raise AttributeError('The function "list_and_tuple" should exists') 27 | 28 | @pytest.mark.it('The function "list_and_tuple" should return a tuple second') 29 | def test_function_return_a_tuple(app): 30 | try: 31 | value = app.list_and_tuple() 32 | assert isinstance(value, tuple) 33 | assert isinstance(value[1], tuple) 34 | except AttributeError: 35 | raise AttributeError('The function "list_and_tuple" should exists') 36 | 37 | @pytest.mark.it('The function "list_and_tuple" should return a list and tuple with the expected values') 38 | def test_function_return_the_expected_values(app): 39 | try: 40 | value = app.list_and_tuple(1,2,3,4,5,6) 41 | assert value[0]==['1', '2', '3', '4', '5', '6'] 42 | assert value[1]==('1', '2', '3', '4', '5', '6') 43 | except AttributeError: 44 | raise AttributeError('The function "list_and_tuple" should exists') 45 | 46 | @pytest.mark.it('The function "list_and_tuple" should return a list and tuple with the expected values') 47 | def test_function_return_the_expected_values(app): 48 | try: 49 | value = app.list_and_tuple(7,8,9,10,11,12) 50 | assert value[0]==['7', '8', '9', '10', '11', '12'] 51 | assert value[1]==('7', '8', '9', '10', '11', '12') 52 | except AttributeError: 53 | raise AttributeError('The function "list_and_tuple" should exists') 54 | -------------------------------------------------------------------------------- /exercises/024-class-with-two-methods/README.es.md: -------------------------------------------------------------------------------- 1 | # `024` Class with two methods 2 | 3 | ## 📝 Instrucciones: 4 | 5 | 1. Define una clase llamada `InputOutString` que tenga al menos dos métodos: 6 | + `get_string` para obtener un string de entrada desde la consola. 7 | + `print_string` para imprimir el string obtenido en mayúsculas. 8 | 9 | 2. Prueba los métodos de tu clase. 10 | 11 | ## 💡 Pista: 12 | 13 | + Usa el método `__init__` para construir tus parámetros. 14 | -------------------------------------------------------------------------------- /exercises/024-class-with-two-methods/README.md: -------------------------------------------------------------------------------- 1 | # `024` Class with two methods 2 | 3 | ## 📝 Instructions: 4 | 5 | 1. Define a class called `InputOutString` which has at least two methods: 6 | + `get_string` to get a string from console input. 7 | + `print_string` to print the string in upper case. 8 | 9 | 2. Test your class' methods. 10 | 11 | ## 💡 Hint: 12 | 13 | + Use the `__init__` method to construct your parameters. 14 | -------------------------------------------------------------------------------- /exercises/024-class-with-two-methods/app.py: -------------------------------------------------------------------------------- 1 | # Your code here 2 | -------------------------------------------------------------------------------- /exercises/024-class-with-two-methods/solution.hide.py: -------------------------------------------------------------------------------- 1 | # Your code here 2 | class InputOutString: 3 | def __init__(self): 4 | self.input_string = "" 5 | 6 | def get_string(self): 7 | self.input_string = input("Enter a string: ") 8 | 9 | def print_string(self): 10 | print(self.input_string.upper()) 11 | 12 | string_object = InputOutString() 13 | string_object.get_string() 14 | string_object.print_string() 15 | -------------------------------------------------------------------------------- /exercises/024-class-with-two-methods/test.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | import os 3 | import re 4 | import io 5 | import sys 6 | import mock 7 | 8 | path = os.path.dirname(os.path.abspath(__file__))+'/app.py' 9 | 10 | 11 | @pytest.mark.it('Use the function print()') 12 | def test_for_file_output(capsys): 13 | with open(path, 'r') as content_file: 14 | content = content_file.read() 15 | pattern = (r"print\s*\(") 16 | regex = re.compile(pattern) 17 | assert bool(regex.search(content)) == True 18 | 19 | 20 | @pytest.mark.it("String input should be uppercase") 21 | @mock.patch('builtins.input', lambda x: 'hello') 22 | def test_plus_ten(stdin): 23 | sys.stdout = buffer = io.StringIO() 24 | import app 25 | captured = buffer.getvalue() 26 | assert "HELLO\n" in captured 27 | -------------------------------------------------------------------------------- /exercises/025-print-formula/README.es.md: -------------------------------------------------------------------------------- 1 | # `025` Print formula 2 | 3 | ## 📝 Instrucciones: 4 | 5 | 1. Escribe una función llamada `print_formula()`, con un parámetro que calcule e imprima el valor según la fórmula dada. 6 | 7 | ```text 8 | Q = Square root of (2 * c * d) / h 9 | ``` 10 | 11 | *A continuación encontrarás los valores fijos de `c` y `h`:* 12 | 13 | + `c` es 50. 14 | + `h` es 30. 15 | + `d` sería el parámetro de la función. 16 | 17 | ## 📎 Ejemplo de entrada: 18 | 19 | ```py 20 | print_formula(150) 21 | ``` 22 | 23 | ## 📎 Ejemplo de salida: 24 | 25 | ```py 26 | 22 27 | ``` 28 | 29 | ## 💡 Pistas: 30 | 31 | + Si el resultado recibido es un decimal, debería redondearse a su valor más cercano (por ejemplo, si el resultado es 26.0, debiese imprimirse como 26). 32 | 33 | + Importa el módulo `math`. 34 | -------------------------------------------------------------------------------- /exercises/025-print-formula/README.md: -------------------------------------------------------------------------------- 1 | # `025` Print formula 2 | 3 | ## 📝 Instructions: 4 | 5 | 1. Write a function `print_formula()`, with one parameter that calculates and prints the value according to the given formula: 6 | 7 | ```text 8 | Q = Square root of (2 * c * d) / h 9 | ``` 10 | 11 | *Following are the fixed values of `c` and `h`:* 12 | 13 | + `c` is 50. 14 | + `h` is 30. 15 | + `d` would be the parameter of the function. 16 | 17 | ## 📎 Example input: 18 | 19 | ```py 20 | print_formula(150) 21 | ``` 22 | 23 | ## 📎 Example output: 24 | 25 | ```py 26 | 22 27 | ``` 28 | 29 | ## 💡 Hints: 30 | 31 | + If the output received is in decimal form, it should be rounded off to its nearest value (for example, if the output received is 26.0, it should be printed as 26). 32 | 33 | + Import the `math` module. 34 | -------------------------------------------------------------------------------- /exercises/025-print-formula/app.py: -------------------------------------------------------------------------------- 1 | # Your code here 2 | -------------------------------------------------------------------------------- /exercises/025-print-formula/solution.hide.py: -------------------------------------------------------------------------------- 1 | # Your code here 2 | import math 3 | 4 | def print_formula(d): 5 | return round(math.sqrt(2 * 50 * d / 30)) 6 | 7 | print(print_formula(150)) 8 | -------------------------------------------------------------------------------- /exercises/025-print-formula/test.py: -------------------------------------------------------------------------------- 1 | import pytest, io, sys, json, mock, re, os 2 | path = os.path.dirname(os.path.abspath(__file__))+'/app.py' 3 | 4 | @pytest.mark.it('The function print_formula must exist') 5 | def test_function_existence(capsys, app): 6 | assert app.print_formula 7 | 8 | @pytest.mark.it('The solution should work as expected. Testing with 100') 9 | def test_expected_output(capsys, app): 10 | assert app.print_formula(100) == 18 11 | 12 | @pytest.mark.it('The solution should work as expected. Testing with 90') 13 | def test_another_output(capsys, app): 14 | assert app.print_formula(90) == 17 15 | 16 | -------------------------------------------------------------------------------- /exercises/026-two-dimensional-array/README.es.md: -------------------------------------------------------------------------------- 1 | # `026` Two dimensional list 2 | 3 | ## 📝 Instrucciones: 4 | 5 | 1. Escribe una función llamada `two_dimensional_list()` que tome 2 dígitos (x, y) como entrada y genere una lista bidimensional o matriz. 6 | 7 | 2. El valor del elemento en la fila `i` y columna `j` de la lista debería ser `i*j` (los valores de sus índices). 8 | 9 | ## 📎 Ejemplo de entrada: 10 | 11 | ```py 12 | two_dimensional_list(3,5) 13 | ``` 14 | 15 | ## 📎 Ejemplo de salida: 16 | 17 | ```py 18 | [[0, 0, 0, 0, 0], [0, 1, 2, 3, 4], [0, 2, 4, 6, 8]] 19 | ``` 20 | -------------------------------------------------------------------------------- /exercises/026-two-dimensional-array/README.md: -------------------------------------------------------------------------------- 1 | # `026` Two dimensional list 2 | 3 | ## 📝 Instructions: 4 | 5 | 1. Write a function `two_dimensional_list()`, that takes 2 digits (x, y) as input and generates a 2-dimensional list or matrix. 6 | 7 | 2. The element value in the `i` row and `j` column of the list should be `i*j` (their index values). 8 | 9 | ## 📎 Example input: 10 | 11 | ```py 12 | two_dimensional_list(3,5) 13 | ``` 14 | 15 | ## 📎 Example output: 16 | 17 | ```py 18 | [[0, 0, 0, 0, 0], [0, 1, 2, 3, 4], [0, 2, 4, 6, 8]] 19 | ``` 20 | 21 | -------------------------------------------------------------------------------- /exercises/026-two-dimensional-array/app.py: -------------------------------------------------------------------------------- 1 | # Your code here 2 | -------------------------------------------------------------------------------- /exercises/026-two-dimensional-array/solution.hide.py: -------------------------------------------------------------------------------- 1 | # Your code here 2 | def two_dimensional_list(n_rows, n_columns): 3 | dimensions = [int(x) for x in "{},{}".format(n_rows, n_columns).split(',')] 4 | row_num = dimensions[0] 5 | col_num = dimensions[1] 6 | matrix = [[0 for col in range(col_num)] for row in range(row_num)] 7 | 8 | for row in range(row_num): 9 | for col in range(col_num): 10 | matrix[row][col] = row * col 11 | 12 | return matrix 13 | 14 | print(two_dimensional_list(3,5)) 15 | -------------------------------------------------------------------------------- /exercises/026-two-dimensional-array/test.py: -------------------------------------------------------------------------------- 1 | import pytest,os,re,io,sys, mock, json 2 | 3 | @pytest.mark.it('The function two_dimensional_list must exist') 4 | def test_function_existence(capsys, app): 5 | assert app.two_dimensional_list 6 | 7 | @pytest.mark.it('The function should return the expected output') 8 | def test_expected_output(capsys, app): 9 | assert app.two_dimensional_list(3,5) == [[0, 0, 0, 0, 0], [0, 1, 2, 3, 4], [0, 2, 4, 6, 8]] 10 | 11 | @pytest.mark.it('The function should work with other entries. Testing with (2, 7)') 12 | def test_expected_output(capsys, app): 13 | assert app.two_dimensional_list(2,7) == [[0, 0, 0, 0, 0, 0, 0], [0, 1, 2, 3, 4, 5, 6]] 14 | 15 | @pytest.mark.it('The function should work with other entries. Testing with (1, 10)') 16 | def test_expected_output(capsys, app): 17 | assert app.two_dimensional_list(1,10) == [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]] 18 | -------------------------------------------------------------------------------- /exercises/027-sequence-of-words/README.es.md: -------------------------------------------------------------------------------- 1 | # `027` Sequence of words 2 | 3 | ## 📝 Instrucciones: 4 | 5 | 1. Escribe una función llamada `sequence_of_words()`, que acepte una secuencia de palabras separadas por comas como entrada (un string). 6 | 7 | 2. Imprime las palabras en una secuencia separada por comas después de ordenarlas alfabéticamente. 8 | 9 | ## 📎 Ejemplo de entrada: 10 | 11 | ```py 12 | sequence_of_words("without,hello,bag,world") 13 | ``` 14 | 15 | ## 📎 Ejemplo de salida: 16 | 17 | ```py 18 | bag, hello, without, world 19 | ``` 20 | 21 | ## 💡 Pista: 22 | 23 | + Recuerda que cada palabra debe estar separada por una coma y dentro de UN SOLO par de comillas. 24 | -------------------------------------------------------------------------------- /exercises/027-sequence-of-words/README.md: -------------------------------------------------------------------------------- 1 | # `027` Sequence of words 2 | 3 | ## 📝 Instructions: 4 | 5 | 1. Write a function `sequence_of_words`, that accepts a comma separated sequence of words as input (a string). 6 | 7 | 2. Print the words in a comma-separated sequence after sorting them alphabetically. 8 | 9 | ## 📎 Example input: 10 | 11 | ```py 12 | sequence_of_words("without,hello,bag,world") 13 | ``` 14 | 15 | ## 📎 Example output: 16 | 17 | ```py 18 | bag, hello, without, world 19 | ``` 20 | 21 | ## 💡 Hint: 22 | 23 | + Remember that each word must be separated by a comma and inside ONLY ONE pair of quotes. 24 | -------------------------------------------------------------------------------- /exercises/027-sequence-of-words/app.py: -------------------------------------------------------------------------------- 1 | # Your code here 2 | -------------------------------------------------------------------------------- /exercises/027-sequence-of-words/solution.hide.py: -------------------------------------------------------------------------------- 1 | # Your code here 2 | def sequence_of_words(words): 3 | items=[x for x in "{}".format(words).split(',')] 4 | items.sort() 5 | return (','.join(items)) 6 | 7 | print(sequence_of_words("this,is,sorted")) 8 | -------------------------------------------------------------------------------- /exercises/027-sequence-of-words/test.py: -------------------------------------------------------------------------------- 1 | import pytest, io, sys, json, mock, re, os 2 | path = os.path.dirname(os.path.abspath(__file__))+'/app.py' 3 | 4 | @pytest.mark.it('The function sequence_of_words must exist') 5 | def test_function_existence(capsys, app): 6 | assert app.sequence_of_words 7 | 8 | @pytest.mark.it('The function should return the expected output') 9 | def test_function_existence(capsys, app): 10 | assert app.sequence_of_words("bag,hello,without,world") == "bag,hello,without,world" 11 | 12 | @pytest.mark.it('The function should return the expected output. Testing with different values') 13 | def test_function_existence(capsys, app): 14 | assert app.sequence_of_words("No,pain,gain") == "No,gain,pain" 15 | -------------------------------------------------------------------------------- /exercises/028-sequence-of-lines/README.es.md: -------------------------------------------------------------------------------- 1 | # `028` Sequence of lines 2 | 3 | ## 📝 Instrucciones: 4 | 5 | 1. Escribe la función `lines()`. Dado un string, haz que la función retorne todos los caracteres del string en mayúsculas. 6 | 7 | ## 📎 Ejemplo de entrada: 8 | 9 | ```py 10 | lines("Hello world, practice makes perfect") 11 | ``` 12 | 13 | ## 📎 Ejemplo de salida: 14 | 15 | ```text 16 | HELLO WORLD, PRACTICE MAKES PERFECT 17 | ``` 18 | 19 | ## 💡 Pista: 20 | 21 | + Googlea cómo convertir un string a mayúsculas en Python. 22 | -------------------------------------------------------------------------------- /exercises/028-sequence-of-lines/README.md: -------------------------------------------------------------------------------- 1 | # `028` Sequence of lines 2 | 3 | ## 📝 Instructions: 4 | 5 | 1. Write a function `lines()`. Given a string, make the function return all the characters from the string capitalized. 6 | 7 | ## 📎 Example input: 8 | 9 | ```py 10 | lines("Hello world, practice makes perfect") 11 | ``` 12 | 13 | ## 📎 Example output: 14 | 15 | ```text 16 | HELLO WORLD, PRACTICE MAKES PERFECT 17 | ``` 18 | 19 | ## 💡 Hint: 20 | 21 | + Google how to capitalize a string in Python. 22 | -------------------------------------------------------------------------------- /exercises/028-sequence-of-lines/app.py: -------------------------------------------------------------------------------- 1 | # Your code here 2 | -------------------------------------------------------------------------------- /exercises/028-sequence-of-lines/solution.hide.py: -------------------------------------------------------------------------------- 1 | # Your code here 2 | def lines(text): 3 | return text.upper() 4 | 5 | print(lines('Hello world, practice makes perfect')) 6 | -------------------------------------------------------------------------------- /exercises/028-sequence-of-lines/test.py: -------------------------------------------------------------------------------- 1 | import pytest, io, sys, json, mock, re, os 2 | path = os.path.dirname(os.path.abspath(__file__))+'/app.py' 3 | 4 | @pytest.mark.it('The function lines must exist') 5 | def test_function_existence(capsys, app): 6 | assert app.lines 7 | 8 | @pytest.mark.it('The function should return the expected output') 9 | def test_expected_output(capsys, app): 10 | assert app.lines("hello world") == "HELLO WORLD" 11 | 12 | @pytest.mark.it('The function should return the expected output. Testing with a different value') 13 | def test_another_output(capsys, app): 14 | assert app.lines("LeT the WOrld know YoU") == "LET THE WORLD KNOW YOU" 15 | -------------------------------------------------------------------------------- /exercises/029-remove-duplicate-words/README.es.md: -------------------------------------------------------------------------------- 1 | # `029` Remove duplicate words 2 | 3 | ## 📝 Instrucciones: 4 | 5 | 1. Escribe la función `remove_duplicate_words()` que tome una secuencia de palabras separadas por espacios en blanco como entrada. Luego, retorna las palabras eliminando duplicados y organizándolas alfanuméricamente. 6 | 7 | ## 📎 Ejemplo de entrada: 8 | 9 | ```py 10 | remove_duplicate_words("hello world and practice makes perfect and hello world again") 11 | ``` 12 | 13 | ## 📎 Ejemplo de salida: 14 | 15 | ```text 16 | again and hello makes perfect practice world 17 | ``` 18 | 19 | ## 💡 Pistas: 20 | 21 | + Puedes convertir tu entrada en el tipo de dato `set` para eliminar automáticamente cualquier duplicado. 22 | 23 | + Puedes utilizar `sorted()` para ordenar los elementos de una lista. 24 | -------------------------------------------------------------------------------- /exercises/029-remove-duplicate-words/README.md: -------------------------------------------------------------------------------- 1 | # `029` Remove duplicate words 2 | 3 | ## 📝 Instructions: 4 | 5 | 1. Write a function called `remove_duplicate_words()` that accepts a sequence of whitespace separated words as input and returns the words after removing all duplicate words and sorting them alphanumerically. 6 | 7 | ## 📎 Example input: 8 | 9 | ```py 10 | remove_duplicate_words("hello world and practice makes perfect and hello world again") 11 | ``` 12 | 13 | ## 📎 Example output: 14 | 15 | ```text 16 | again and hello makes perfect practice world 17 | ``` 18 | 19 | ## 💡 Hints: 20 | 21 | + You can convert your input into the `set` data type to automatically eliminate duplicates. 22 | 23 | + You can use `sorted()` to sort the data from a list. 24 | -------------------------------------------------------------------------------- /exercises/029-remove-duplicate-words/app.py: -------------------------------------------------------------------------------- 1 | # Your code here 2 | -------------------------------------------------------------------------------- /exercises/029-remove-duplicate-words/solution.hide.py: -------------------------------------------------------------------------------- 1 | # Your code here 2 | def remove_duplicate_words(text): 3 | words = text.split() 4 | return (" ".join(sorted(list(set(words))))) 5 | 6 | print(remove_duplicate_words("hello world and practice makes perfect and hello world again")) 7 | -------------------------------------------------------------------------------- /exercises/029-remove-duplicate-words/test.py: -------------------------------------------------------------------------------- 1 | import pytest, io, sys, json, mock, re, os 2 | 3 | @pytest.mark.it('The function remove_duplicate_words must exist') 4 | def test_function_existence(capsys, app): 5 | app.remove_duplicate_words 6 | 7 | @pytest.mark.it('The function should return the expected output') 8 | def test_expected_output(capsys, app): 9 | assert app.remove_duplicate_words("hello world and practice makes perfect and hello world again") == "again and hello makes perfect practice world" 10 | 11 | @pytest.mark.it('The function should work with other entries. Testing with different values') 12 | def test_expected_output_2(capsys, app): 13 | assert app.remove_duplicate_words("lets try this again with another try") == "again another lets this try with" 14 | 15 | @pytest.mark.it('The function should work with other entries. Testing with different values') 16 | def test_expected_output_3(capsys, app): 17 | assert app.remove_duplicate_words("Jacke was Named Jacke by his mother") == "Jacke Named by his mother was" 18 | 19 | -------------------------------------------------------------------------------- /exercises/030-divisable-binary/README.es.md: -------------------------------------------------------------------------------- 1 | # `030` Divisable binary 2 | 3 | ## 📝 Instrucciones: 4 | 5 | 1. Escribe la función `divisible_binary()` que tome una secuencia de números binarios de 4 dígitos separados por comas como entrada y verifique si son divisibles por 5. Imprime los números que son divisibles por 5 en una secuencia separada por comas. 6 | 7 | ## 📎 Ejemplo de entrada: 8 | 9 | ```py 10 | divisible_binary("0100,0011,1010,1001") 11 | ``` 12 | 13 | ## 📎 Ejemplo de salida: 14 | 15 | ```py 16 | 1010 17 | ``` 18 | 19 | ## 💡 Pista: 20 | 21 | + Para convertir números binarios en nuestros números enteros cotidianos (base 10 o decimal), es necesario incluir la base del número que ingresamos en el primer argumento (en este caso, base 2 o binario), y la función `int()` se encargará del resto. Sería así: 22 | 23 | ```py 24 | binary = '0101' 25 | decimal = int(binary, 2) 26 | 27 | print(decimal) # Output: 5 28 | ``` 29 | -------------------------------------------------------------------------------- /exercises/030-divisable-binary/README.md: -------------------------------------------------------------------------------- 1 | # `030` Divisable binary 2 | 3 | ## 📝 Instructions: 4 | 5 | 1. Write a function `divisible_binary()` that takes a sequence of comma-separated 4-digit binary numbers as input and checks if they are divisible by 5. Print the numbers that are divisible by 5 in a comma-separated sequence. 6 | 7 | ## 📎 Example input: 8 | 9 | ```py 10 | divisible_binary("0100,0011,1010,1001") 11 | ``` 12 | 13 | ## 📎 Example output: 14 | 15 | ```py 16 | 1010 17 | ``` 18 | 19 | ## 💡 Hint: 20 | 21 | + To convert binary numbers into our everyday integer numbers (base 10 or decimal), you have to include the base of the number we input in the first argument (in this case, base 2 or binary), and the function `int()` will take care of the rest. Like this: 22 | 23 | ```py 24 | binary = '0101' 25 | decimal = int(binary, 2) 26 | 27 | print(decimal) # Output: 5 28 | ``` 29 | -------------------------------------------------------------------------------- /exercises/030-divisable-binary/app.py: -------------------------------------------------------------------------------- 1 | # Your code here 2 | -------------------------------------------------------------------------------- /exercises/030-divisable-binary/solution.hide.py: -------------------------------------------------------------------------------- 1 | # Your code here 2 | def divisible_binary(binary_sequence): 3 | divisible_numbers = [] 4 | binary_numbers = [x for x in binary_sequence.split(',')] 5 | for binary_num in binary_numbers: 6 | int_binary_num = int(binary_num, 2) 7 | if not int_binary_num % 5: 8 | divisible_numbers.append(binary_num) 9 | 10 | return ','.join(divisible_numbers) 11 | 12 | print(divisible_binary("1000,1100,1010,1111")) 13 | -------------------------------------------------------------------------------- /exercises/030-divisable-binary/test.py: -------------------------------------------------------------------------------- 1 | import pytest, io, sys, json, mock, re, os 2 | 3 | @pytest.mark.it('The function divisible_binary must exist') 4 | def test_function_existence(capsys, app): 5 | assert app.divisible_binary 6 | 7 | @pytest.mark.it('The function should return the expected output') 8 | def test_expected_output(capsys, app): 9 | assert app.divisible_binary("0100,0011,1010,1001") == "1010" 10 | 11 | @pytest.mark.it('The function should work with other parameters. testing with 1111,1000,0101,0000') 12 | def test_expected_output_2(capsys, app): 13 | assert app.divisible_binary("1111,1000,0101,0000") == "1111,0101,0000" 14 | 15 | @pytest.mark.it("The function should work with other parameters. Testing with 1000") 16 | def test_expected_output_3(capsys, app): 17 | assert app.divisible_binary("1000,1000,1000,1000") == "" 18 | -------------------------------------------------------------------------------- /exercises/031-sum-eigth-digit/README.es.md: -------------------------------------------------------------------------------- 1 | # `031` All digits even 2 | 3 | ## 📝 Instrucciones: 4 | 5 | 1. Define una función llamada `all_digits_even()` para identificar e imprimir todos los números entre 1000 y 3000 (inclusive) en los que cada dígito es un número par. Muestra los números resultantes en una secuencia separada por comas en una sola línea. 6 | -------------------------------------------------------------------------------- /exercises/031-sum-eigth-digit/README.md: -------------------------------------------------------------------------------- 1 | # `031` All digits even 2 | 3 | ## 📝 Instructions: 4 | 5 | 1. Define a function named `all_digits_even()` to identify and print all numbers between 1000 and 3000 (inclusive) where each digit is an even number. Display the resulting numbers in a comma-separated sequence on a single line. 6 | -------------------------------------------------------------------------------- /exercises/031-sum-eigth-digit/app.py: -------------------------------------------------------------------------------- 1 | # Your code here 2 | -------------------------------------------------------------------------------- /exercises/031-sum-eigth-digit/solution.hide.py: -------------------------------------------------------------------------------- 1 | # Your code here 2 | def all_digits_even(): 3 | values = [] 4 | for i in range(1000, 3001): 5 | s = str(i) 6 | if (int(s[0]) % 2 == 0) and (int(s[1]) % 2 == 0) and (int(s[2]) % 2 == 0) and (int(s[3]) % 2 == 0): 7 | values.append(s) 8 | 9 | return ",".join(values) 10 | 11 | print(all_digits_even()) 12 | -------------------------------------------------------------------------------- /exercises/032-numbers-of-letters-and-digits/README.es.md: -------------------------------------------------------------------------------- 1 | # `032` Number of letters and digits 2 | 3 | ## 📝 Instrucciones: 4 | 5 | 1. Escribe una función llamada `letters_and_digits()` que tome una oración como entrada y calcule la cantidad de letras y dígitos presentes en ella. 6 | 7 | ## 📎 Ejemplo de entrada: 8 | 9 | ```py 10 | letters_and_digits("hello world! 123") 11 | ``` 12 | 13 | ## 📎 Ejemplo de salida: 14 | 15 | ```text 16 | LETTERS 10 17 | DIGITS 3 18 | ``` 19 | 20 | ## 💡 Pista: 21 | 22 | + Declara un diccionario para guardar ambas cuentas en una sola variable. 23 | -------------------------------------------------------------------------------- /exercises/032-numbers-of-letters-and-digits/README.md: -------------------------------------------------------------------------------- 1 | # `032` Number of letters and digits 2 | 3 | ## 📝 Instructions: 4 | 5 | 1. Write a function named `letters_and_digits()` that takes a sentence as input and calculates the number of letters and digits present in it. 6 | 7 | ## 📎 Example input: 8 | 9 | ```py 10 | letters_and_digits("hello world! 123") 11 | ``` 12 | 13 | ## 📎 Example output: 14 | 15 | ```text 16 | LETTERS 10 17 | DIGITS 3 18 | ``` 19 | 20 | ## 💡 Hint: 21 | 22 | + Declare a dictionary for storing both counts in one variable. 23 | -------------------------------------------------------------------------------- /exercises/032-numbers-of-letters-and-digits/app.py: -------------------------------------------------------------------------------- 1 | # Your code here 2 | -------------------------------------------------------------------------------- /exercises/032-numbers-of-letters-and-digits/solution.hide.py: -------------------------------------------------------------------------------- 1 | # Your code here 2 | def letters_and_digits(text): 3 | counts = {"DIGITS": 0, "LETTERS": 0} 4 | for char in text: 5 | if char.isdigit(): 6 | counts["DIGITS"] += 1 7 | elif char.isalpha(): 8 | counts["LETTERS"] += 1 9 | else: 10 | pass 11 | 12 | return f"LETTERS {counts['LETTERS']} DIGITS {counts['DIGITS']}" 13 | 14 | print(letters_and_digits("hello world! 123")) 15 | -------------------------------------------------------------------------------- /exercises/032-numbers-of-letters-and-digits/test.py: -------------------------------------------------------------------------------- 1 | import mock, pytest, io, sys 2 | 3 | 4 | @pytest.mark.it('The function letters_and_digits must exist') 5 | def test_function_existence(capsys, app): 6 | assert app.letters_and_digits 7 | 8 | @pytest.mark.it('The function should return the expected output') 9 | def test_output(capsys, app): 10 | app.letters_and_digits("hello world! 123") == "LETTERS 10 DIGITS 3" 11 | 12 | @pytest.mark.it('The solution should work with other parameters') 13 | def test_another_entry(capsys, app): 14 | assert app.letters_and_digits("My name is C200 and i live in apartment 3H") == "LETTERS 29 DIGITS 4" 15 | -------------------------------------------------------------------------------- /exercises/033-number-of-uppercase/README.es.md: -------------------------------------------------------------------------------- 1 | # `033` Number of uppercase 2 | 3 | ## 📝 Instrucciones: 4 | 5 | 1. Escribe una función llamada `number_of_uppercase()` que acepte una frase y calcule la cantidad de letras en mayúsculas (uppercase) y minúsculas (lowercase). 6 | 7 | ## 📎 Ejemplo de entrada: 8 | 9 | ```py 10 | number_of_uppercase("Hello world!") 11 | ``` 12 | 13 | ## 📎 Ejemplo de salida: 14 | 15 | ```text 16 | UPPERCASE 1 17 | LOWERCASE 9 18 | ``` 19 | 20 | ## 💡 Pista: 21 | 22 | + Declara un diccionario para guardar ambas cuentas en una sola variable. 23 | -------------------------------------------------------------------------------- /exercises/033-number-of-uppercase/README.md: -------------------------------------------------------------------------------- 1 | # `033` Number of uppercase 2 | 3 | ## 📝 Instructions: 4 | 5 | 1. Write a program `number_of_uppercase()` that accepts a sentence and calculates the number of uppercase and lowercase letters. 6 | 7 | ## 📎 Example input: 8 | 9 | ```py 10 | number_of_uppercase("Hello world!") 11 | ``` 12 | 13 | ## 📎 Example output: 14 | 15 | ```text 16 | UPPERCASE 1 17 | LOWERCASE 9 18 | ``` 19 | 20 | ## 💡 Hint: 21 | 22 | + Declare a dictionary for storing both counts in one variable. 23 | -------------------------------------------------------------------------------- /exercises/033-number-of-uppercase/app.py: -------------------------------------------------------------------------------- 1 | # Your code here 2 | -------------------------------------------------------------------------------- /exercises/033-number-of-uppercase/solution.hide.py: -------------------------------------------------------------------------------- 1 | # Your code here 2 | def number_of_uppercase(string): 3 | counts = {"UPPERCASE": 0, "LOWERCASE": 0} 4 | for char in string: 5 | if char.isupper(): 6 | counts["UPPERCASE"] += 1 7 | elif char.islower(): 8 | counts["LOWERCASE"] += 1 9 | else: 10 | pass 11 | 12 | return f"UPPERCASE {counts['UPPERCASE']} LOWERCASE {counts['LOWERCASE']}" 13 | 14 | print(number_of_uppercase("Hello world!")) 15 | -------------------------------------------------------------------------------- /exercises/034-a_aa_aaa_aaaa/README.es.md: -------------------------------------------------------------------------------- 1 | # `034` a aa aaa aaaa 2 | 3 | ## 📝 Instrucciones: 4 | 5 | 1. Escribe un programa llamado `computed_value()` para calcular la suma de a+aa+aaa+aaaa, donde 'a' es un dígito dado. 6 | 7 | ## 📎 Ejemplo de entrada: 8 | 9 | ```py 10 | computed_value(9) 11 | ``` 12 | 13 | ## 📎 Ejemplo de salida: 14 | 15 | ```py 16 | 11106 17 | ``` 18 | -------------------------------------------------------------------------------- /exercises/034-a_aa_aaa_aaaa/README.md: -------------------------------------------------------------------------------- 1 | # `034` a aa aaa aaaa 2 | 3 | ## 📝 Instructions: 4 | 5 | 1. Write a program `computed_value()` to calculate the sum of a+aa+aaa+aaaa, where 'a' is a given digit. 6 | 7 | ## 📎 Example input: 8 | 9 | ```py 10 | computed_value(9) 11 | ``` 12 | 13 | ## 📎 Example output: 14 | 15 | ```py 16 | 11106 17 | ``` 18 | -------------------------------------------------------------------------------- /exercises/034-a_aa_aaa_aaaa/app.py: -------------------------------------------------------------------------------- 1 | # Your code here 2 | -------------------------------------------------------------------------------- /exercises/034-a_aa_aaa_aaaa/solution.hide.py: -------------------------------------------------------------------------------- 1 | # Your code here 2 | def computed_value(param): 3 | result = 0 4 | for i in range(1, 5): 5 | concatenated_number = int(str(param) * i) 6 | result += concatenated_number 7 | return result 8 | 9 | print(computed_value(9)) 10 | -------------------------------------------------------------------------------- /exercises/034-a_aa_aaa_aaaa/test.py: -------------------------------------------------------------------------------- 1 | import io, sys, pytest, os, re, mock 2 | 3 | @pytest.mark.it('The function computed_value must exist') 4 | def test_function_existence(capsys, app): 5 | assert app.computed_value 6 | 7 | @pytest.mark.it('The function should return the expected output') 8 | def test_expected_output(capsys, app): 9 | assert app.computed_value(9) == 11106 10 | 11 | @pytest.mark.it('The function should work with other inputs. Testing with 123') 12 | def test_another_output(capsys, app): 13 | assert app.computed_value(123) == 123246369492 14 | 15 | @pytest.mark.it('The function should work with other inputs. Testing with 0') 16 | def test_with_zero(capsys, app): 17 | assert app.computed_value(0) == 0 18 | -------------------------------------------------------------------------------- /exercises/035-square-each-odd-number/README.es.md: -------------------------------------------------------------------------------- 1 | # `035` Square odd numbers 2 | 3 | ## 📝 Instrucciones: 4 | 5 | 1. Escribe una función llamada `square_odd_numbers()` que acepte un string de números separados por comas como entrada, eleve al cuadrado solo los números impares y devuelva los resultados en una lista. 6 | 7 | ## 📎 Ejemplo de entrada: 8 | 9 | ```py 10 | square_odd_numbers("1,2,3,4,5,6,7,8,9") 11 | ``` 12 | 13 | ## 📎 Ejemplo de salida: 14 | 15 | ```py 16 | [1, 9, 25, 49, 81] 17 | ``` 18 | -------------------------------------------------------------------------------- /exercises/035-square-each-odd-number/README.md: -------------------------------------------------------------------------------- 1 | # `035` Square odd numbers 2 | 3 | ## 📝 Instructions: 4 | 5 | 1. Write a function named `square_odd_numbers()` that accepts a string of comma-separated numbers as input, squares only the odd numbers, and returns the results as a list. 6 | 7 | ## 📎 Example input: 8 | 9 | ```py 10 | square_odd_numbers("1,2,3,4,5,6,7,8,9") 11 | ``` 12 | 13 | ## 📎 Example output: 14 | 15 | ```py 16 | [1, 9, 25, 49, 81] 17 | ``` 18 | -------------------------------------------------------------------------------- /exercises/035-square-each-odd-number/app.py: -------------------------------------------------------------------------------- 1 | # Your code here 2 | -------------------------------------------------------------------------------- /exercises/035-square-each-odd-number/solution.hide.py: -------------------------------------------------------------------------------- 1 | # Your code here 2 | def square_odd_numbers(numbers_str): 3 | numbers_list = numbers_str.split(',') 4 | squared_odd_numbers = [] 5 | 6 | for num_str in numbers_list: 7 | if num_str.isdigit(): 8 | num = int(num_str) 9 | 10 | if num % 2 != 0: 11 | squared_odd_numbers.append(num**2) 12 | 13 | return squared_odd_numbers 14 | 15 | print(square_odd_numbers("1,2,3,4,5,6,7")) 16 | 17 | 18 | ### SOLUTION 2 ### (List Comprehension) 19 | 20 | # def square_odd_numbers(numbers): 21 | # number_list = [int(num) for num in numbers.split(',')] 22 | # squared_odd_numbers = [num**2 for num in number_list if num % 2 != 0] 23 | 24 | # return squared_odd_numbers 25 | 26 | # print(square_odd_numbers("1,2,3,4,5,6,7")) 27 | -------------------------------------------------------------------------------- /exercises/036-net-amount/README.es.md: -------------------------------------------------------------------------------- 1 | # `036` Net amount 2 | 3 | ## 📝 Instrucciones: 4 | 5 | 1. Escribe una función llamada `net_amount()` que calcule el saldo neto de una cuenta bancaria basándose en un registro de transacciones ingresado por parámetro. El formato del registro de transacciones se muestra a continuación: 6 | 7 | + D 100 8 | + W 200 9 | 10 | `D` significa depósito y `W` significa retiro. 11 | 12 | ## 📎 Ejemplo de entrada: 13 | 14 | ```py 15 | net_amount("D 300 D 300 W 200 D 100") 16 | ``` 17 | 18 | ## 📎 Ejemplo de salida: 19 | 20 | ```py 21 | 500 22 | ``` 23 | -------------------------------------------------------------------------------- /exercises/036-net-amount/README.md: -------------------------------------------------------------------------------- 1 | # `036` Net amount 2 | 3 | ## 📝 Instructions: 4 | 5 | 1. Write a function named `net_amount()` that computes the net amount of a bank account based on a transaction log from input. The transaction log format is shown as following: 6 | 7 | + D 100 8 | + W 200 9 | 10 | `D` means deposit while `W` means withdrawal. 11 | 12 | ## 📎 Example input: 13 | 14 | ```py 15 | net_amount("D 300 D 300 W 200 D 100") 16 | ``` 17 | 18 | ## 📎 Example output: 19 | 20 | ```py 21 | 500 22 | ``` 23 | -------------------------------------------------------------------------------- /exercises/036-net-amount/app.py: -------------------------------------------------------------------------------- 1 | # Your code here 2 | -------------------------------------------------------------------------------- /exercises/036-net-amount/solution.hide.py: -------------------------------------------------------------------------------- 1 | # Your code here 2 | def net_amount(param): 3 | total = 0 4 | values = param.split() 5 | for x in range(len(values)): 6 | if values[x] == 'D': 7 | total+=int(values[x+1]) 8 | elif values[x] == 'W': 9 | total-=int(values[x+1]) 10 | return total 11 | 12 | print(net_amount("D 300 W 200 D 400")) 13 | -------------------------------------------------------------------------------- /exercises/036-net-amount/test.py: -------------------------------------------------------------------------------- 1 | import pytest, io, sys, json, mock, re, os 2 | path = os.path.dirname(os.path.abspath(__file__))+'/app.py' 3 | 4 | @pytest.mark.it('The function net_amount must exist') 5 | def test_function_existence(capsys, app): 6 | assert app.net_amount 7 | 8 | @pytest.mark.it('The solution should return the expected output') 9 | def test_output(capsys, app): 10 | assert app.net_amount("D 300 D 300 W 200 D 100") == 500 11 | 12 | @pytest.mark.it('The solution should work with other parameters. Testing with "W 300 D 300 W 200 D 300"') 13 | def test_output_2(capsys, app): 14 | assert app.net_amount("W 300 D 300 W 200 D 300") == 100 15 | 16 | @pytest.mark.it('The solution should work with other parameters. Testing with "W 300 D 300 W 200 D 300"') 17 | def test_output_negative(capsys, app): 18 | assert app.net_amount("W 300 D 300 W 200 W 300") == -500 19 | -------------------------------------------------------------------------------- /exercises/037-validity-of-password/README.es.md: -------------------------------------------------------------------------------- 1 | # `037` Validity of password 2 | 3 | ## 📝 Instrucciones: 4 | 5 | Un sitio web requiere que los usuarios ingresen un nombre de usuario y una contraseña para registrarse. Escribe una función llamada `valid_password()` para verificar la validez de la contraseña ingresada por los usuarios. A continuación, se detallan los criterios para verificar la contraseña: 6 | 7 | 1. Al menos 1 letra entre [a-z]. 8 | 2. Al menos 1 número entre [0-9]. 9 | 3. Al menos 1 letra entre [A-Z]. 10 | 4. Al menos 1 carácter de [$#@]. 11 | 5. Longitud mínima de la contraseña: 6. 12 | 6. Longitud máxima de la contraseña: 12. 13 | 14 | Tu programa debe aceptar una contraseña y verificarla según los criterios anteriores. Si la contraseña es validada correctamente, la función devuelve el siguiente string `"Valid password"`, de lo contrario devuelve `"Invalid password. Please try again"`. 15 | 16 | ## 📎 Ejemplo de entrada: 17 | 18 | ```py 19 | valid_password("ABd1234@1") 20 | ``` 21 | 22 | ## 📎 Ejemplo de salida: 23 | 24 | ```py 25 | "Valid password" 26 | ``` 27 | 28 | ## 💡 Pistas: 29 | 30 | + Lee sobre expresiones regulares en Python. 31 | 32 | + Necesitarás importar el módulo 're' (regular expressions) para poder usar la función `search()`. 33 | 34 | + Para importarlo, copia y pega lo siguiente al inicio de tu archivo `import re`. 35 | -------------------------------------------------------------------------------- /exercises/037-validity-of-password/README.md: -------------------------------------------------------------------------------- 1 | # `037` Validity of password 2 | 3 | ## 📝 Instructions: 4 | 5 | A website requires the users to input a username and password to register. Write a function named `valid_password()` to check the validity of password input by users. Following are the criteria for checking the password: 6 | 7 | 1. At least 1 letter between [a-z]. 8 | 2. At least 1 number between [0-9]. 9 | 3. At least 1 letter between [A-Z]. 10 | 4. At least 1 character from [$#@]. 11 | 5. Minimum length of password: 6. 12 | 6. Maximum length of password: 12. 13 | 14 | Your program should accept a password and verify it according to the previous criteria. If the password is successfully validated, the function returns the following string `"Valid password"`. Otherwise, it returns `"Invalid password. Please try again"`. 15 | 16 | ## 📎 Example input: 17 | 18 | ```py 19 | valid_password("ABd1234@1") 20 | ``` 21 | 22 | ## 📎 Example output: 23 | 24 | ```py 25 | "Valid password" 26 | ``` 27 | 28 | ## 💡 Hints: 29 | 30 | + Read about regular expressions in Python. 31 | 32 | + You will need to import the 're' module (regular expressions) to be able to use the `search()` function. 33 | 34 | + To import it, copy and paste the following at the beginning of your file: `import re`. 35 | -------------------------------------------------------------------------------- /exercises/037-validity-of-password/app.py: -------------------------------------------------------------------------------- 1 | # Your code here 2 | -------------------------------------------------------------------------------- /exercises/037-validity-of-password/solution.hide.py: -------------------------------------------------------------------------------- 1 | # Your code here 2 | import re 3 | 4 | def valid_password(password): 5 | pattern = re.compile(r'^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[$#@]).{6,12}$') 6 | 7 | if not pattern.match(password): 8 | return "Invalid password. Please try again" 9 | else: 10 | return "Valid password" 11 | 12 | 13 | print(valid_password("ABd1234@1")) 14 | -------------------------------------------------------------------------------- /exercises/037-validity-of-password/test.py: -------------------------------------------------------------------------------- 1 | import pytest, io, sys, json, mock, re, os 2 | path = os.path.dirname(os.path.abspath(__file__))+'/app.py' 3 | 4 | 5 | @pytest.mark.it('The function valid_password must exist') 6 | def test_function_existence(capsys, app): 7 | assert app.valid_password 8 | 9 | @pytest.mark.it('The function should return the expected output') 10 | def test_expected_output(capsys, app): 11 | assert app.valid_password("ABd1234@1") == "Valid password" 12 | 13 | @pytest.mark.it('Your solution should work as expected for valid passwords') 14 | def test_expected_another_output(capsys, app): 15 | assert app.valid_password("Lmd4567@2") == "Valid password" 16 | 17 | @pytest.mark.it('Your solution should work as expected when there is no valid password input') 18 | def test_expected_output_no_valid_entries(capsys, app): 19 | assert app.valid_password("ABd12") == "Invalid password. Please try again" 20 | -------------------------------------------------------------------------------- /exercises/038-sort-tuples-ascending/README.es.md: -------------------------------------------------------------------------------- 1 | # `038` Sort Tuples Ascending 2 | 3 | ## 📝 Instrucciones: 4 | 5 | Escribe una función llamada `sort_tuples_ascending()` para ordenar las tuplas (`name`, `age`, `score`) en orden ascendente, donde `name`, `age` y `score` son strings. El criterio de orden es: 6 | 7 | 1. Ordenar según el nombre. 8 | 2. Luego, ordenar según la edad. 9 | 3. Después, ordenar por puntuación. 10 | 11 | La prioridad es `name` > `age` > `score`. 12 | 13 | ## 📎 Ejemplo de entrada: 14 | 15 | ```py 16 | sort_tuples_ascending(['Tom,19,80', 'John,20,90', 'Jony,17,91', 'Jony,17,93', 'Jason,21,85']) 17 | ``` 18 | 19 | ## 📎 Ejemplo de salida: 20 | 21 | ```py 22 | [('John', '20', '90'), ('Jony', '17', '91'), ('Jony', '17', '93'), ('Jason', '21', '85'), ('Tom', '19', '80')] 23 | ``` 24 | 25 | ## 💡 Pistas: 26 | 27 | + Utilizamos `itemgetter` para habilitar múltiples claves de orden. 28 | 29 | + Observa que la salida es una lista con tuplas en su interior. 30 | -------------------------------------------------------------------------------- /exercises/038-sort-tuples-ascending/README.md: -------------------------------------------------------------------------------- 1 | # `038` Sort Tuples Ascending 2 | 3 | ## 📝 Instructions: 4 | 5 | Write a function `sort_tuples_ascending()` to sort the (`name`, `age`, `score`) tuples by ascending order, where `name`, `age` and `score` are all strings. The sort criteria is: 6 | 7 | 1. Sort based on name. 8 | 2. Then sort based on age. 9 | 3. Then sort by score. 10 | 11 | The priority is `name` > `age` > `score`. 12 | 13 | ## 📎 Example input: 14 | 15 | ```py 16 | sort_tuples_ascending(['Tom,19,80', 'John,20,90', 'Jony,17,91', 'Jony,17,93', 'Jason,21,85']) 17 | ``` 18 | 19 | ## 📎 Example output: 20 | 21 | ```py 22 | [('Jason', '21', '85'), ('John', '20', '90'), ('Jony', '17', '91'), ('Jony', '17', '93'), ('Tom', '19', '80')] 23 | ``` 24 | 25 | ## 💡 Hints: 26 | 27 | + We use `itemgetter` to enable multiple sort keys. 28 | 29 | + Notice that the output is a list with tuples inside. 30 | -------------------------------------------------------------------------------- /exercises/038-sort-tuples-ascending/app.py: -------------------------------------------------------------------------------- 1 | from operator import itemgetter 2 | 3 | # Your code here 4 | -------------------------------------------------------------------------------- /exercises/038-sort-tuples-ascending/solution.hide.py: -------------------------------------------------------------------------------- 1 | from operator import itemgetter 2 | 3 | # Your code here 4 | def sort_tuples_ascending(data): 5 | tuples_list = [tuple(entry.split(',')) for entry in data] 6 | 7 | sorted_tuples = sorted(tuples_list, key=itemgetter(0, 1, 2)) 8 | 9 | return sorted_tuples 10 | 11 | example_input = [ 12 | 'Tom,19,80', 13 | 'John,20,90', 14 | 'Jony,17,91', 15 | 'Jony,17,93', 16 | 'Jason,21,85' 17 | ] 18 | 19 | result = sort_tuples_ascending(example_input) 20 | print(result) 21 | -------------------------------------------------------------------------------- /exercises/038-sort-tuples-ascending/test.py: -------------------------------------------------------------------------------- 1 | import pytest, io, sys, json, mock, re, os 2 | 3 | path = os.path.dirname(os.path.abspath(__file__))+'/app.py' 4 | 5 | @pytest.mark.it('The function sort_tuples_ascending must exist') 6 | def test_function_existence(capsys, app): 7 | assert app.sort_tuples_ascending 8 | 9 | @pytest.mark.it('The function should return the expected output') 10 | def test_expected_output(capsys, app): 11 | assert app.sort_tuples_ascending([ 12 | 'Tom,19,80', 13 | 'John,20,90', 14 | 'Jony,17,91', 15 | 'Jony,17,93', 16 | 'Jason,21,85' 17 | ]) == [('Jason', '21', '85'), ('John', '20', '90'), ('Jony', '17', '91'), ('Jony', '17', '93'), ('Tom', '19', '80')] 18 | 19 | @pytest.mark.it('The solution should work with other entries') 20 | def test_another_entry(capsys, app): 21 | assert app.sort_tuples_ascending([ 22 | 'Martin,23,30', 23 | 'Tomas,25,27' 24 | ]) == [('Martin', '23', '30'), ('Tomas', '25', '27')] 25 | -------------------------------------------------------------------------------- /exercises/039-class-that-iterates/README.es.md: -------------------------------------------------------------------------------- 1 | # `039` Class that iterates 2 | 3 | ## 📝 Instrucciones: 4 | 5 | 1. Define una clase con una *generator function* que pueda iterar los números que son divisibles por 7 en un rango dado de `0` a `n`. 6 | 7 | ## 💡 Pistas: 8 | 9 | + Lee sobre *generator functions* y `yield`: https://sentry.io/answers/python-yield-keyword/ 10 | 11 | + Debes usar `yield` en tu solución. 12 | -------------------------------------------------------------------------------- /exercises/039-class-that-iterates/README.md: -------------------------------------------------------------------------------- 1 | # `039` Class that iterates 2 | 3 | ## 📝 Instructions: 4 | 5 | 1. Define a class with a generator function that can iterate the numbers that are divisible by 7 between a given range `0` and `n`. 6 | 7 | ## 💡 Hints: 8 | 9 | + Read about generator functions and `yield`: https://sentry.io/answers/python-yield-keyword/ 10 | 11 | + You must use `yield` on your solution. 12 | -------------------------------------------------------------------------------- /exercises/039-class-that-iterates/app.py: -------------------------------------------------------------------------------- 1 | # Your code here 2 | -------------------------------------------------------------------------------- /exercises/039-class-that-iterates/solution.hide.py: -------------------------------------------------------------------------------- 1 | class DivisibleBySevenIterator: 2 | def __init__(self, n): 3 | self.n = n 4 | 5 | def generate_divisible_by_seven(self): 6 | for number in range(self.n + 1): 7 | if number % 7 == 0: 8 | yield number 9 | 10 | 11 | n_value = 50 12 | divisible_by_seven_iterator = DivisibleBySevenIterator(n_value) 13 | 14 | for num in divisible_by_seven_iterator.generate_divisible_by_seven(): 15 | print(num) 16 | -------------------------------------------------------------------------------- /exercises/040-compute-robot-distance/README.es.md: -------------------------------------------------------------------------------- 1 | # `040` Compute robot distance 2 | 3 | ## 📝 Instrucciones: 4 | 5 | Un robot se mueve en un plano comenzando desde el punto de inicio (0,0). El robot puede moverse hacia ARRIBA (UP), ABAJO (DOWN), IZQUIERDA (LEFT) y DERECHA (RIGHT) con pasos dados por parámetro. La traza del movimiento del robot se muestra como una lista de la siguiente manera: 6 | 7 | ```py 8 | ["UP 5", "DOWN 3", "LEFT 3", "RIGHT 2"] 9 | ``` 10 | 11 | Los números después de la dirección son los pasos. Por favor, escribe un programa llamado `compute_robot_distance()` para calcular la distancia final después de una secuencia de movimientos desde el punto original. Si la distancia es un número decimal, simplemente imprime el entero más cercano. 12 | 13 | ## 📎 Ejemplo de entrada: 14 | 15 | ```py 16 | compute_robot_distance(["UP 5", "DOWN 3", "LEFT 3", "RIGHT 2"]) 17 | ``` 18 | 19 | ## 📎 Ejemplo de salida: 20 | 21 | ```py 22 | 2 23 | ``` 24 | -------------------------------------------------------------------------------- /exercises/040-compute-robot-distance/README.md: -------------------------------------------------------------------------------- 1 | # `040` Compute robot distance 2 | 3 | ## 📝 Instructions: 4 | 5 | A robot moves in a plane starting from the original point (0,0). The robot can move toward UP, DOWN, LEFT and RIGHT with given steps. The trace of robot movement is shown as a list like the following: 6 | 7 | ```py 8 | ["UP 5", "DOWN 3", "LEFT 3", "RIGHT 2"] 9 | ``` 10 | 11 | The numbers after the direction are steps. Please write a program named `compute_robot_distance()` to compute the final distance after a sequence of movements from the original point. If the distance is a float, then just print the nearest integer. 12 | 13 | ## 📎 Example input: 14 | 15 | ```py 16 | compute_robot_distance(["UP 5", "DOWN 3", "LEFT 3", "RIGHT 2"]) 17 | ``` 18 | 19 | ## 📎 Example output: 20 | 21 | ```py 22 | 2 23 | ``` 24 | -------------------------------------------------------------------------------- /exercises/040-compute-robot-distance/app.py: -------------------------------------------------------------------------------- 1 | # Your code here 2 | -------------------------------------------------------------------------------- /exercises/040-compute-robot-distance/solution.hide.py: -------------------------------------------------------------------------------- 1 | # Your code here 2 | def compute_robot_distance(movements): 3 | x, y = 0, 0 4 | 5 | for move in movements: 6 | direction, steps = move.split() 7 | steps = int(steps) 8 | 9 | if direction == "UP": 10 | y += steps 11 | elif direction == "DOWN": 12 | y -= steps 13 | elif direction == "LEFT": 14 | x -= steps 15 | elif direction == "RIGHT": 16 | x += steps 17 | 18 | distance = (x**2 + y**2)**0.5 19 | rounded_distance = round(distance) 20 | 21 | return rounded_distance 22 | 23 | print(compute_robot_distance(["UP 5", "DOWN 3", "LEFT 3", "RIGHT 2"])) 24 | -------------------------------------------------------------------------------- /exercises/040-compute-robot-distance/test.py: -------------------------------------------------------------------------------- 1 | import pytest, io, sys, json, mock, re, os 2 | 3 | @pytest.mark.it('The function compute_robot_distance must exist') 4 | def test_function_existence(capsys, app): 5 | assert app.compute_robot_distance 6 | 7 | @pytest.mark.it('The function should return the expected output') 8 | def test_expected_output(capsys, app): 9 | movements_list = ["UP 5", "DOWN 3", "LEFT 3", "RIGHT 2"] 10 | assert app.compute_robot_distance(movements_list) == 2 11 | 12 | @pytest.mark.it('The solution should work with other entries') 13 | def test_another_output(capsys, app): 14 | movements_list = ["DOWN 20", "UP 5", "LEFT 5", "RIGHT 2"] 15 | assert app.compute_robot_distance(movements_list) == 15 16 | 17 | @pytest.mark.it('The solution should work with negative inputs') 18 | def test_negative_inputs(capsys, app): 19 | movements_list = ["DOWN -1", "UP -5", "LEFT 50", "RIGHT 20"] 20 | assert app.compute_robot_distance(movements_list) == 30 21 | -------------------------------------------------------------------------------- /exercises/041-frequency-of-words/README.es.md: -------------------------------------------------------------------------------- 1 | # `041` Frequency of words 2 | 3 | ## 📝 Instrucciones: 4 | 5 | 1. Escribe una función llamada `compute_word_frequency()` para calcular la frecuencia de las palabras a partir de un string de entrada. 6 | 7 | 2. Coloca cada palabra separada por un espacio en un diccionario y cuenta su frecuencia. 8 | 9 | 3. Ordena el diccionario alfanuméricamente e imprime en la consola cada clave en una nueva línea. 10 | 11 | ## 📎 Ejemplo de entrada: 12 | 13 | ```py 14 | compute_word_frequency("New to Python or choosing between Python 2 and Python 3? Read Python 2 or Python 3.") 15 | ``` 16 | 17 | ## 📎 Ejemplo de salida: 18 | 19 | ```text 20 | 2: 2 21 | 3.: 1 22 | 3?: 1 23 | New: 1 24 | Python: 5 25 | Read: 1 26 | and: 1 27 | between: 1 28 | choosing: 1 29 | or: 2 30 | to: 1 31 | ``` 32 | 33 | ## 💡 Pista: 34 | 35 | + Puedes poner cada palabra de un string en una lista con el método `split()`, luego te será mucho más fácil trabajar en la solución. 36 | -------------------------------------------------------------------------------- /exercises/041-frequency-of-words/README.md: -------------------------------------------------------------------------------- 1 | # `041` Frequency of words 2 | 3 | ## 📝 Instructions: 4 | 5 | 1. Write a function called `compute_word_frequency()` to compute the frequency of the words from a string input. 6 | 7 | 2. Put each word separated by a space in a dictionary and count its frequency. 8 | 9 | 3. Sort the dictionary alphanumerically and print in the console each key in a new line. 10 | 11 | ## 📎 Example input: 12 | 13 | ```py 14 | compute_word_frequency("New to Python or choosing between Python 2 and Python 3? Read Python 2 or Python 3.") 15 | ``` 16 | 17 | ## 📎 Example output: 18 | 19 | ```text 20 | 2: 2 21 | 3.: 1 22 | 3?: 1 23 | New: 1 24 | Python: 5 25 | Read: 1 26 | and: 1 27 | between: 1 28 | choosing: 1 29 | or: 2 30 | to: 1 31 | ``` 32 | 33 | ## 💡 Hint: 34 | 35 | + You can put each word of a string in a list with the `split()` method, then it is easier to work on it. 36 | -------------------------------------------------------------------------------- /exercises/041-frequency-of-words/app.py: -------------------------------------------------------------------------------- 1 | # Your code here 2 | -------------------------------------------------------------------------------- /exercises/041-frequency-of-words/solution.hide.py: -------------------------------------------------------------------------------- 1 | # Your code here 2 | def compute_word_frequency(sentence): 3 | words = sentence.split() 4 | 5 | word_frequency = {} 6 | 7 | for word in words: 8 | word_frequency[word] = word_frequency.get(word, 0) + 1 9 | 10 | sorted_word_frequency = sorted(word_frequency.items(), key=lambda x: x[0]) 11 | 12 | for word, frequency in sorted_word_frequency: 13 | print(f"{word}: {frequency}") 14 | 15 | 16 | input_sentence = "New to Python or choosing between Python 2 and Python 3? Read Python 2 or Python 3." 17 | compute_word_frequency(input_sentence) 18 | -------------------------------------------------------------------------------- /exercises/041-frequency-of-words/test.py: -------------------------------------------------------------------------------- 1 | import pytest, io, sys, json, mock, re, os 2 | 3 | path = os.path.dirname(os.path.abspath(__file__))+'/app.py' 4 | 5 | @pytest.mark.it('The solution should return the expected output') 6 | def test_convert_inputs(capsys, app): 7 | 8 | fake_input = ["New to Python or choosing between Python 2 and Python 3? Read Python 2 or Python 3"] #fake input 9 | with mock.patch('builtins.input', lambda x: fake_input.pop()): 10 | app() 11 | captured = capsys.readouterr() 12 | assert captured.out == "2:2 3.:1 3?:1 New:1 Python:5 Read:1 and:1 between:1 choosing:1 or:2 to:1\n" -------------------------------------------------------------------------------- /exercises/042-understanding_classes/README.es.md: -------------------------------------------------------------------------------- 1 | # `042` understanding classes 2 | 3 | En Python, una clase es una estructura que te permite organizar y encapsular datos y funcionalidades relacionadas. Las clases son una característica fundamental de la programación orientada a objetos (OOP), un paradigma de programación que utiliza objetos para modelar y organizar el código. 4 | 5 | En términos simples, una clase es como un plano o un molde para crear objetos. Un objeto es una instancia específica de una clase que tiene atributos (datos) y métodos (funciones) asociados. Los atributos representan características del objeto, y los métodos representan las acciones que el objeto puede realizar. 6 | 7 | ## 📎 Ejemplo: 8 | 9 | ```py 10 | class Student: 11 | def __init__(self, name, age, grade): # Estos son sus atributos 12 | self.name = name 13 | self.age = age 14 | self.grade = grade 15 | 16 | def introduce(self): # Esto es un método 17 | return f"Hello! I am {self.name}, I am {self.age} years old, and my current grade is {self.grade}." 18 | 19 | def study(self, hours): # Esto es otro método 20 | self.grade += hours * 0.5 21 | return f"After studying for {hours} hours, {self.name}'s new grade is {self.grade}." 22 | 23 | student1 = Student("Ana", 20, 80) 24 | 25 | print(student1.introduce()) 26 | print(student1.study(3)) 27 | ``` 28 | 29 | En este código: 30 | 31 | + La clase `Student` tiene un método `__init__` para inicializar los atributos *name*, *age* y *grade* del estudiante. 32 | + `introduce` es un método que imprime un mensaje presentando al estudiante. 33 | + `study` es un método que simula el acto de estudiar y actualiza la nota del estudiante. 34 | 35 | ## 📝 Instrucciones: 36 | 37 | 1. Para completar este ejercicio, copia el código proporcionado en el ejemplo y pégalo en tu archivo `app.py`. Ejecuta el código y prueba su funcionalidad. Experimenta con modificar diferentes aspectos del código para observar cómo se comporta. Este enfoque práctico te ayudará a comprender la estructura y el comportamiento de la clase `Student`. Una vez que te hayas familiarizado con el código y sus efectos, siéntete libre de pasar al siguiente ejercicio. 38 | 39 | ## 💡 Pistas: 40 | 41 | + Lee un poco sobre la función interna `__init__`: https://www.w3schools.com/python/gloss_python_class_init.asp 42 | 43 | + Si no comprendes la funcionalidad del parámetro `self` en el código que acabas de copiar, tómate un momento para visitar el siguiente enlace donde encontrarás una explicación detallada: [Entendiendo el parámetro 'self'](https://www.geeksforgeeks.org/self-in-python-class/) 44 | -------------------------------------------------------------------------------- /exercises/042-understanding_classes/README.md: -------------------------------------------------------------------------------- 1 | # `042` understanding classes 2 | 3 | In Python, a class is a structure that allows you to organize and encapsulate related data and functionalities. Classes are a fundamental feature of object-oriented programming (OOP), a programming paradigm that uses objects to model and organize code. 4 | 5 | In simple terms, a class is like a blueprint or a template for creating objects. An object is a specific instance of a class that has associated attributes (data) and methods (functions). Attributes represent the characteristics of the object, and methods represent the actions that the object can perform. 6 | 7 | ## 📎 Example: 8 | 9 | ```py 10 | class Student: 11 | def __init__(self, name, age, grade): # These are its attributes 12 | self.name = name 13 | self.age = age 14 | self.grade = grade 15 | 16 | def introduce(self): # This is a method 17 | return f"Hello! I am {self.name}, I am {self.age} years old, and my current grade is {self.grade}." 18 | 19 | def study(self, hours): # This is another method 20 | self.grade += hours * 0.5 21 | return f"After studying for {hours} hours, {self.name}'s new grade is {self.grade}." 22 | 23 | student1 = Student("Ana", 20, 80) 24 | 25 | print(student1.introduce()) 26 | print(student1.study(3)) 27 | ``` 28 | 29 | In this code: 30 | 31 | + The `Student` class has an `__init__` method to initialize the attributes *name*, *age*, and *grade* of the student. 32 | + `introduce` is a method that prints a message introducing the student. 33 | + `study` is a method that simulates the act of studying and updates the student's grade. 34 | 35 | ## 📝 Instructions: 36 | 37 | 1. To complete this exercise, copy the provided code from the example and paste it into your `app.py` file. Execute the code and test its functionality. Experiment with modifying different aspects of the code to observe how it behaves. This hands-on approach will help you understand the structure and behavior of the `Student` class. Once you have familiarized yourself with the code and its effects, feel free to proceed to the next exercise. 38 | 39 | ## 💡 Hints: 40 | 41 | + Read about the `__init__` built-in function: https://www.w3schools.com/python/gloss_python_class_init.asp 42 | 43 | + If you find yourself wondering about the role of the `self` keyword in Python classes, take a moment to visit the following link for a detailed explanation: [Understanding the 'self' Parameter](https://www.geeksforgeeks.org/self-in-python-class/) 44 | -------------------------------------------------------------------------------- /exercises/042-understanding_classes/app.py: -------------------------------------------------------------------------------- 1 | # Your code here 2 | -------------------------------------------------------------------------------- /exercises/042-understanding_classes/solution.hide.py: -------------------------------------------------------------------------------- 1 | # Your code here 2 | class Student: 3 | def __init__(self, name, age, grade): # These are its attributes 4 | self.name = name 5 | self.age = age 6 | self.grade = grade 7 | 8 | def introduce(self): # This is a method 9 | return f"Hello! I am {self.name}, I am {self.age} years old, and my current grade is {self.grade}." 10 | 11 | def study(self, hours): # This is another method 12 | self.grade += hours * 0.5 13 | return f"After studying for {hours} hours, {self.name}'s new grade is {self.grade}." 14 | 15 | student1 = Student("Ana", 20, 80) 16 | 17 | print(student1.introduce()) 18 | print(student1.study(3)) 19 | -------------------------------------------------------------------------------- /exercises/042-understanding_classes/test.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | from app import Student 3 | 4 | @pytest.mark.it("The Student class should exist") 5 | def test_student_class_exists(): 6 | try: 7 | assert Student 8 | except AttributeError: 9 | raise AttributeError("The class 'Student' should exist in app.py") 10 | 11 | @pytest.mark.it("The Student class includes the 'name' attribute") 12 | def test_student_has_name_attribute(): 13 | student = Student("John", 21, 75) 14 | assert hasattr(student, "name") 15 | 16 | @pytest.mark.it("The Student class includes the 'age' attribute") 17 | def test_student_has_age_attribute(): 18 | student = Student("John", 21, 75) 19 | assert hasattr(student, "age") 20 | 21 | @pytest.mark.it("The Student class includes the 'grade' attribute") 22 | def test_student_has_grade_attribute(): 23 | student = Student("John", 21, 75) 24 | assert hasattr(student, "grade") 25 | 26 | @pytest.mark.it("The Student class includes the 'introduce' method") 27 | def test_student_has_introduce_method(): 28 | student = Student("Alice", 22, 90) 29 | assert hasattr(student, "introduce") 30 | 31 | @pytest.mark.it("The introduce method should return the expected string. Testing with different values") 32 | def test_student_introduce_method_returns_expected_string(): 33 | student1 = Student("Alice", 22, 90) 34 | student2 = Student("Bob", 19, 85) 35 | assert student1.introduce() == "Hello! I am Alice, I am 22 years old, and my current grade is 90." 36 | assert student2.introduce() == "Hello! I am Bob, I am 19 years old, and my current grade is 85." 37 | 38 | @pytest.mark.it("The Student class includes the 'study' method") 39 | def test_student_has_study_method(): 40 | student = Student("John", 21, 75) 41 | assert hasattr(student, "study") 42 | 43 | @pytest.mark.it("The study method should return the expected string. Testing with different values") 44 | def test_student_study_method_returns_expected_string(): 45 | student1 = Student("Eve", 20, 78) 46 | student2 = Student("Charlie", 23, 88) 47 | assert student1.study(3) == "After studying for 3 hours, Eve's new grade is 79.5." 48 | assert student2.study(2) == "After studying for 2 hours, Charlie's new grade is 89.0." 49 | -------------------------------------------------------------------------------- /exercises/042.1-init_and_str_methods/README.es.md: -------------------------------------------------------------------------------- 1 | # `042.1` `__init__` and `__str__` methods 2 | 3 | Normalmente, al trabajar con clases, te encontrarás con métodos de este estilo `____`; estos son conocidos como "métodos mágicos". Existen varios de ellos, y cada uno desempeña una función específica. En esta ocasión, nos enfocaremos en aprender dos de los más fundamentales. 4 | 5 | El método mágico `__init__` es esencial para la inicialización de objetos dentro de una clase. Se ejecuta automáticamente cuando se crea una nueva instancia de la clase, permitiendo la asignación de valores iniciales a los atributos del objeto. 6 | 7 | El método `__str__` se utiliza para proporcionar una representación de cadena legible de la instancia, permitiendo personalizar la salida cuando se imprime el objeto. Esto es especialmente útil para mejorar la legibilidad del código y facilitar la depuración, ya que define una versión amigable para humanos de la información contenida en el objeto. 8 | 9 | ## 📎 Ejemplo: 10 | 11 | ```py 12 | class Person: 13 | def __init__(self, name, age, gender): 14 | self.name = name 15 | self.age = age 16 | self.gender = gender 17 | 18 | def __str__(self): 19 | return f"{self.name}, {self.age} years old, {self.gender}" 20 | 21 | # Create an instance of the Person class 22 | person1 = Person("Juan", 25, "Male") 23 | 24 | # Print the information of the person using the __str__ method 25 | print(person1) # Output: Juan, 25 years old, Male 26 | ``` 27 | 28 | ## 📝 Instrucciones: 29 | 30 | 1. Crea una clase llamada `Book` que tenga los métodos `__init__` y `__str__`. 31 | 32 | 2. El método `__init__` debe inicializar los atributos `title`, `author` y `year`. 33 | 34 | 3. El método `__str__` debe devolver una cadena que represente la información de una instancia del siguiente libro de esta manera: 35 | 36 | ```py 37 | book1 = ("The Great Gatsby", "F. Scott Fitzgerald", 1925) 38 | 39 | print(book1) 40 | 41 | # Output: 42 | # 43 | # Book Title: The Great Gatsby 44 | # Author: F. Scott Fitzgerald 45 | # Year: 1925 46 | ``` 47 | 48 | ## 💡 Pistas: 49 | 50 | + Utiliza el método `__init__` para inicializar los atributos de la instancia. 51 | 52 | + Utiliza el método `__str__` para proporcionar una representación de cadena legible de la instancia. 53 | 54 | + Para hacer saltos de línea dentro de un string puedes usar los siguientes caracteres `\n`. -------------------------------------------------------------------------------- /exercises/042.1-init_and_str_methods/README.md: -------------------------------------------------------------------------------- 1 | # `042.1` `__init__` and `__str__` methods 2 | 3 | Typically, when working with classes, you will encounter methods of the form `____`; these are known as "magic methods." There are a lot of them, each serving a specific purpose. This time, we will focus on learning two of the most fundamental ones. 4 | 5 | The magic method `__init__` is essential for the initialization of objects within a class. It is automatically executed when a new instance of the class is created, allowing for the assignment of initial values to the object's attributes. 6 | 7 | The `__str__` method is used to provide a readable string representation of the instance, allowing customization of the output when the object is printed. This is especially useful for improving code readability and facilitating debugging, as it defines a human-friendly version of the information contained in the object. 8 | 9 | ## 📎 Example: 10 | 11 | ```py 12 | class Person: 13 | def __init__(self, name, age, gender): 14 | self.name = name 15 | self.age = age 16 | self.gender = gender 17 | 18 | def __str__(self): 19 | return f"{self.name}, {self.age} years old, {self.gender}" 20 | 21 | # Create an instance of the Person class 22 | person1 = Person("Juan", 25, "Male") 23 | 24 | # Print the information of the person using the __str__ method 25 | print(person1) # Output: Juan, 25 years old, Male 26 | ``` 27 | 28 | ## 📝 Instructions: 29 | 30 | 1. Create a class called `Book` that has the `__init__` and `__str__` methods. 31 | 32 | 2. The `__init__` method should initialize the `title`, `author`, and `year` attributes. 33 | 34 | 3. The `__str__` method should return a string representing the information of an instance of the following book in this manner: 35 | 36 | ```py 37 | book1 = ("The Great Gatsby", "F. Scott Fitzgerald", 1925) 38 | 39 | print(book1) 40 | 41 | # Output: 42 | # 43 | # Book Title: The Great Gatsby 44 | # Author: F. Scott Fitzgerald 45 | # Year: 1925 46 | ``` 47 | 48 | ## 💡 Hints: 49 | 50 | + Use the `__init__` method to initialize the instance's attributes. 51 | 52 | + Use the `__str__` method to provide a readable string representation of the instance. 53 | 54 | + To create line breaks within a string, you can use the `\n` characters. -------------------------------------------------------------------------------- /exercises/042.1-init_and_str_methods/app.py: -------------------------------------------------------------------------------- 1 | # Your code here 2 | 3 | -------------------------------------------------------------------------------- /exercises/042.1-init_and_str_methods/solution.hide.py: -------------------------------------------------------------------------------- 1 | # Your code here 2 | 3 | class Book: 4 | def __init__(self, title, author, year): 5 | self.title = title 6 | self.author = author 7 | self.year = year 8 | 9 | def __str__(self): 10 | return f"Book Title: {self.title}\nAuthor: {self.author}\nYear: {self.year}" 11 | 12 | book1 = Book("The Great Gatsby", "F. Scott Fitzgerald", 1925) 13 | 14 | print(book1) -------------------------------------------------------------------------------- /exercises/042.1-init_and_str_methods/test.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | from app import Book 3 | 4 | @pytest.mark.it("The Book class exists") 5 | def test_book_class_exists(): 6 | try: 7 | assert Book 8 | except AttributeError: 9 | raise AttributeError("The class 'Book' should exist in app.py") 10 | 11 | @pytest.mark.it("The Book class has the __init__ method") 12 | def test_book_has_init_method(): 13 | assert hasattr(Book, "__init__") 14 | 15 | @pytest.mark.it("The __init__ method initializes the title, author, and year attributes") 16 | def test_init_method_initializes_attributes(): 17 | book = Book("The Great Gatsby", "F. Scott Fitzgerald", 1925) 18 | assert hasattr(book, "title") 19 | assert hasattr(book, "author") 20 | assert hasattr(book, "year") 21 | 22 | @pytest.mark.it("The Book class has the __str__ method") 23 | def test_book_has_str_method(): 24 | assert hasattr(Book, "__str__") 25 | 26 | @pytest.mark.it("The __str__ method returns the expected string") 27 | def test_str_method_returns_expected_string(capsys): 28 | book = Book("The Great Gatsby", "F. Scott Fitzgerald", 1925) 29 | print(book) 30 | captured = capsys.readouterr() 31 | expected_output = "Book Title: The Great Gatsby\nAuthor: F. Scott Fitzgerald\nYear: 1925\n" 32 | assert captured.out == expected_output 33 | 34 | -------------------------------------------------------------------------------- /exercises/043-inheritance_and_polymorphism/README.es.md: -------------------------------------------------------------------------------- 1 | # `043` Inheritance and polymorphism 2 | 3 | Ahora que entendemos qué es una clase y algunas de sus características, hablemos sobre dos nuevos conceptos relacionados con las clases: herencia y polimorfismo. Considera el siguiente ejemplo: 4 | 5 | ```py 6 | class HighSchoolStudent(Student): # Agrega la clase padre dentro de los paréntesis 7 | def __init__(self, name, age, grade, specialization): 8 | super().__init__(name, age, grade) 9 | self.specialization = specialization 10 | 11 | def study(self, hours): 12 | return f"{self.name} is a high school student specializing in {self.specialization} and is studying for {hours} hours for exams." 13 | 14 | # Creando una instancia de HighSchoolStudent 15 | high_school_student = HighSchoolStudent("John", 16, 85, "Science") 16 | print(high_school_student.introduce()) # Podemos llamar a este método gracias a la herencia 17 | print(high_school_student.study(4)) # Este método ha sido ligeramente modificado y ahora retorna un string diferente 18 | ``` 19 | 20 | Suponiendo que la clase `Student` del ejercicio anterior está definida justo encima de esta clase `HighSchoolStudent`, para heredar sus métodos y atributos, simplemente incluimos el nombre de la clase que queremos heredar (la clase padre) dentro de los paréntesis de la clase hija (`HighSchoolStudent`). Como puedes ver, ahora podemos usar el método `introduce` de la clase `Student` sin tener que codificarlo nuevamente, haciendo nuestro código más eficiente. Lo mismo se aplica a los atributos; no necesitamos redefinirlos. 21 | 22 | Además, tenemos la flexibilidad de agregar nuevos métodos exclusivamente para esta clase o incluso sobreescribir un método heredado si es necesario, como se demuestra en el método `study` que está ligeramente modificado con respecto a la clase `Student`; esto se llama **polimorfismo**. 23 | 24 | ## 📝 Instrucciones: 25 | 26 | 1. Crea una clase llamada `CollegeStudent` que herede de la clase `Student` ya definida. 27 | 28 | 2. Agrega un nuevo atributo llamado `major` para representar la carrera que están estudiando. 29 | 30 | 3. Modifica el método heredado `introduce` para retornar este string: 31 | 32 | ```py 33 | "Hi there! I'm , a college student majoring in ." 34 | ``` 35 | 36 | 4. Agrega un nuevo método llamado `attend_lecture` que retorne el siguiente string: 37 | 38 | ```py 39 | " is attending a lecture for students." 40 | ``` 41 | 42 | 5. Crea una instancia de tu nueva clase y llama a cada uno de sus métodos. Ejecuta tu código para asegurarte de que funcione. 43 | 44 | 45 | ## 💡 Pista: 46 | 47 | + Puede que hayas notado el uso de un nuevo método `super()`, que es necesario para heredar de una clase padre. Observa dónde se encuentra ubicado y lee más sobre él aquí: [Entendiendo super() en Python](https://realpython.com/python-super/). 48 | -------------------------------------------------------------------------------- /exercises/043-inheritance_and_polymorphism/README.md: -------------------------------------------------------------------------------- 1 | # `043` Inheritance and polymorphism 2 | 3 | Now that we understand what a class is and some of its characteristics, let's talk about two new concepts related to classes: inheritance and polymorphism. Consider the following example: 4 | 5 | ```py 6 | class HighSchoolStudent(Student): # Add the parent class inside the parenthesis 7 | def __init__(self, name, age, grade, specialization): 8 | super().__init__(name, age, grade) 9 | self.specialization = specialization 10 | 11 | def study(self, hours): 12 | return f"{self.name} is a high school student specializing in {self.specialization} and is studying for {hours} hours for exams." 13 | 14 | # Creating an instance of HighSchoolStudent 15 | high_school_student = HighSchoolStudent("John", 16, 85, "Science") 16 | print(high_school_student.introduce()) # We can call this method thanks to inheritance 17 | print(high_school_student.study(4)) # This method has been slightly modified and now it returns a different string 18 | ``` 19 | 20 | Assuming that the `Student` class from the previous exercise is coded just above this `HighSchoolStudent` class, to inherit its methods and attributes, we simply include the name of the class we want to inherit from (the parent class) inside the parentheses of the child class (`HighSchoolStudent`). As you can see, we can now use the `introduce` method from the `Student` class without having to code it again, making our code more efficient. The same applies to attributes; we don't need to redefine them. 21 | 22 | Additionally, we have the flexibility to add new methods exclusively for this class or even override an inherited method if needed, as demonstrated in the `study` method, which is slightly modified from the `Student` method; this is called **polymorphism**. 23 | 24 | ## 📝 Instructions: 25 | 26 | 1. Create a class called `CollegeStudent` which inherits from the already defined `Student` class. 27 | 28 | 2. Add a new attribute called `major` to represent the major they are studying. 29 | 30 | 3. Modify the inherited `introduce` method to return this string: 31 | 32 | ```py 33 | "Hi there! I'm , a college student majoring in ." 34 | ``` 35 | 36 | 4. Add a new method called `attend_lecture` that returns the following string: 37 | 38 | ```py 39 | " is attending a lecture for students." 40 | ``` 41 | 42 | 5. Create an instance of your newly created class and call each of its methods. Execute your code to ensure it works. 43 | 44 | ## 💡 Hint: 45 | 46 | + You may have noticed the use of a new method `super()` which is necessary for inheriting from a parent class. Take a look at where it is positioned and have a read about it: [Understanding Python's super()](https://realpython.com/python-super/). 47 | -------------------------------------------------------------------------------- /exercises/043-inheritance_and_polymorphism/app.py: -------------------------------------------------------------------------------- 1 | ### DON'T modify this code ### 2 | 3 | class Student: 4 | def __init__(self, name, age, grade): 5 | self.name = name 6 | self.age = age 7 | self.grade = grade 8 | 9 | def introduce(self): 10 | return f"Hello! I am {self.name}, I am {self.age} years old, and my current grade is {self.grade}." 11 | 12 | def study(self, hours): 13 | return f"{self.name} is studying for {hours} hours." 14 | 15 | ### DON'T modify the code above ### 16 | 17 | ### ↓ Your code here ↓ ### 18 | -------------------------------------------------------------------------------- /exercises/043-inheritance_and_polymorphism/solution.hide.py: -------------------------------------------------------------------------------- 1 | ### DON'T modify this code ### 2 | 3 | class Student: 4 | def __init__(self, name, age, grade): 5 | self.name = name 6 | self.age = age 7 | self.grade = grade 8 | 9 | def introduce(self): 10 | return f"Hello! I am {self.name}, I am {self.age} years old, and my current grade is {self.grade}." 11 | 12 | def study(self, hours): 13 | return f"{self.name} is studying for {hours} hours." 14 | 15 | ### DON'T modify the code above ### 16 | 17 | ### ↓ Your code here ↓ ### 18 | 19 | class CollegeStudent(Student): 20 | def __init__(self, name, age, grade, major): 21 | super().__init__(name, age, grade) 22 | self.major = major 23 | 24 | def introduce(self): 25 | return f"Hi there! I'm {self.name}, a college student majoring in {self.major}." 26 | 27 | def attend_lecture(self): 28 | return f"{self.name} is attending a lecture for {self.major} students." 29 | 30 | 31 | college_student = CollegeStudent("Alice", 20, 90, "Computer Science") 32 | print(college_student.introduce()) 33 | print(college_student.study(3)) 34 | print(college_student.attend_lecture()) 35 | -------------------------------------------------------------------------------- /exercises/043-inheritance_and_polymorphism/test.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | from app import CollegeStudent 3 | 4 | @pytest.mark.it("The CollegeStudent class should exist") 5 | def test_college_student_class_exists(): 6 | try: 7 | assert CollegeStudent 8 | except AttributeError: 9 | raise AttributeError("The class 'CollegeStudent' should exist in app.py") 10 | 11 | @pytest.mark.it("The CollegeStudent class includes the 'name' attribute") 12 | def test_college_student_has_name_attribute(): 13 | college_student = CollegeStudent("John", 21, 75, "Computer Science") 14 | assert hasattr(college_student, "name") 15 | 16 | @pytest.mark.it("The CollegeStudent class includes the 'age' attribute") 17 | def test_college_student_has_age_attribute(): 18 | college_student = CollegeStudent("John", 21, 75, "Computer Science") 19 | assert hasattr(college_student, "age") 20 | 21 | @pytest.mark.it("The CollegeStudent class includes the 'grade' attribute") 22 | def test_college_student_has_grade_attribute(): 23 | college_student = CollegeStudent("John", 21, 75, "Computer Science") 24 | assert hasattr(college_student, "grade") 25 | 26 | @pytest.mark.it("The CollegeStudent class includes the 'major' attribute") 27 | def test_college_student_has_major_attribute(): 28 | college_student = CollegeStudent("John", 21, 75, "Computer Science") 29 | assert hasattr(college_student, "major") 30 | 31 | @pytest.mark.it("The CollegeStudent class includes the 'introduce' method") 32 | def test_college_student_has_introduce_method(): 33 | college_student = CollegeStudent("Alice", 22, 90, "Computer Science") 34 | assert hasattr(college_student, "introduce") 35 | 36 | @pytest.mark.it("The CollegeStudent class includes the 'study' method") 37 | def test_college_student_has_study_method(): 38 | college_student = CollegeStudent("John", 21, 75, "Computer Science") 39 | assert hasattr(college_student, "study") 40 | 41 | @pytest.mark.it("The CollegeStudent class includes the 'attend_lecture' method") 42 | def test_college_student_has_attend_lecture_method(): 43 | college_student = CollegeStudent("John", 21, 75, "Computer Science") 44 | assert hasattr(college_student, "attend_lecture") 45 | 46 | @pytest.mark.it("The introduce method should return the expected string. Testing with different values") 47 | def test_college_student_introduce_method_returns_expected_string(): 48 | student1 = CollegeStudent("Alice", 22, 90, "Computer Science") 49 | student2 = CollegeStudent("Bob", 19, 85, "Mathematics") 50 | assert student1.introduce() == "Hi there! I'm Alice, a college student majoring in Computer Science." 51 | assert student2.introduce() == "Hi there! I'm Bob, a college student majoring in Mathematics." 52 | 53 | @pytest.mark.it("The study method should return the expected string. Testing with different values") 54 | def test_college_student_study_method_returns_expected_string(): 55 | student1 = CollegeStudent("Eve", 20, 78, "Physics") 56 | student2 = CollegeStudent("Charlie", 23, 88, "Chemistry") 57 | assert student1.study(3) == "Eve is studying for 3 hours." 58 | assert student2.study(2) == "Charlie is studying for 2 hours." 59 | 60 | @pytest.mark.it("The attend_lecture method should return the expected string. Testing with different values") 61 | def test_college_student_attend_lecture_method_returns_expected_string(): 62 | student1 = CollegeStudent("Eve", 20, 78, "Physics") 63 | student2 = CollegeStudent("Charlie", 23, 88, "Chemistry") 64 | assert student1.attend_lecture() == "Eve is attending a lecture for Physics students." 65 | assert student2.attend_lecture() == "Charlie is attending a lecture for Chemistry students." 66 | 67 | -------------------------------------------------------------------------------- /exercises/044-static_methods/README.es.md: -------------------------------------------------------------------------------- 1 | # `044` static methods 2 | 3 | Un **método estático** en Python es un método que está vinculado a una clase en lugar de a una instancia de la clase. A diferencia de los métodos regulares, los métodos estáticos no tienen acceso a la instancia o a la clase en sí. 4 | 5 | Los métodos estáticos se utilizan a menudo cuando un método en particular no depende del estado de la instancia o de la clase. Son más parecidos a funciones de utilidad asociadas con una clase. 6 | 7 | ```py 8 | class Person: 9 | 10 | def __init__(self, name, age): 11 | self.name = name 12 | self.age = age 13 | 14 | @staticmethod 15 | def is_adult(age): 16 | return age >= 18 17 | 18 | # Creando instancias de Person 19 | person1 = Person("Alice", 25) 20 | person2 = Person("Bob", 16) 21 | 22 | # Usando el static method para verificar si una persona es adulta 23 | is_adult_person1 = Person.is_adult(person1.age) 24 | is_adult_person2 = Person.is_adult(person2.age) 25 | print(f"{person1.name} is an adult: {is_adult_person1}") 26 | print(f"{person2.name} is an adult: {is_adult_person2}") 27 | ``` 28 | 29 | En este ejemplo: 30 | 31 | + El método estático `is_adult` verifica si una persona es adulta según su edad. No tiene acceso a variables de instancia o de clase directamente. 32 | 33 | ## 📝 Instrucciones: 34 | 35 | 1. Crea una clase llamada `MathOperations`. 36 | 37 | 2. Crea un método estático llamado `add_numbers` que tome dos números como parámetros y devuelva su suma. 38 | 39 | 3. Crea una instancia de la clase `MathOperations`. 40 | 41 | 4. Utiliza el método estático `add_numbers` para sumar dos números, por ejemplo, 10 y 15. 42 | 43 | 5. Imprime el resultado. 44 | 45 | ## 📎 Ejemplo de entrada: 46 | 47 | ```py 48 | math_operations_instance = MathOperations() 49 | sum_of_numbers = MathOperations.add_numbers(10, 15) 50 | ``` 51 | 52 | ## 📎 Ejemplo de salida: 53 | 54 | ```py 55 | # Sum of Numbers: 25 56 | ``` 57 | 58 | ## 💡 Pistas: 59 | 60 | + Recuerda, para crear un método estático, utiliza el decorador `@staticmethod` encima de la definición del método. 61 | 62 | + Cualquier cosa que aún no entiendas completamente, te animamos a que siempre utilices las herramientas que te ofrece internet para buscar información y aclarar la mayoría de tus dudas (todos los desarrolladores hacen esto, no te preocupes). 63 | -------------------------------------------------------------------------------- /exercises/044-static_methods/README.md: -------------------------------------------------------------------------------- 1 | # `044` static methods 2 | 3 | A **static method** in Python is a method that is bound to a class rather than an instance of the class. Unlike regular methods, static methods don't have access to the instance or class itself. 4 | 5 | Static methods are often used when a particular method does not depend on the state of the instance or the class. They are more like utility functions associated with a class. 6 | 7 | ```py 8 | class Person: 9 | 10 | def __init__(self, name, age): 11 | self.name = name 12 | self.age = age 13 | 14 | @staticmethod 15 | def is_adult(age): 16 | return age >= 18 17 | 18 | # Creating instances of Person 19 | person1 = Person("Alice", 25) 20 | person2 = Person("Bob", 16) 21 | 22 | # Using the static method to check if a person is an adult 23 | is_adult_person1 = Person.is_adult(person1.age) 24 | is_adult_person2 = Person.is_adult(person2.age) 25 | print(f"{person1.name} is an adult: {is_adult_person1}") 26 | print(f"{person2.name} is an adult: {is_adult_person2}") 27 | ``` 28 | 29 | In this example: 30 | 31 | + The static method `is_adult` checks if a person is an adult based on their age. It doesn't have access to instance or class variables directly. 32 | 33 | ## 📝 Instructions: 34 | 35 | 1. Create a class called `MathOperations`. 36 | 37 | 2. Create a static method named `add_numbers` that takes two numbers as parameters and returns their sum. 38 | 39 | 3. Create an instance of the `MathOperations` class. 40 | 41 | 4. Use the static method `add_numbers` to add two numbers, for example, 10 and 15. 42 | 43 | 5. Print the result. 44 | 45 | ## 📎 Example input: 46 | 47 | ```py 48 | math_operations_instance = MathOperations() 49 | sum_of_numbers = MathOperations.add_numbers(10, 15) 50 | ``` 51 | 52 | ## 📎 Example output: 53 | 54 | ```py 55 | # Sum of Numbers: 25 56 | ``` 57 | 58 | ## 💡 Hints: 59 | 60 | + Remember, To create a static method, use the `@staticmethod` decorator above the method definition. 61 | 62 | + For anything you still don't fully get, we encourage you to always use the tools the internet provides you to search for information and clear most of your doubts (all developers do this, don't worry). 63 | -------------------------------------------------------------------------------- /exercises/044-static_methods/app.py: -------------------------------------------------------------------------------- 1 | # Your code here 2 | -------------------------------------------------------------------------------- /exercises/044-static_methods/solution.hide.py: -------------------------------------------------------------------------------- 1 | # Your code here 2 | 3 | class MathOperations: 4 | 5 | @staticmethod 6 | def add_numbers(num1, num2): 7 | return num1 + num2 8 | 9 | # You can call the static method without creating an instance 10 | sum_of_numbers = MathOperations.add_numbers(10, 15) 11 | 12 | print(f"Sum of Numbers: {sum_of_numbers}") 13 | -------------------------------------------------------------------------------- /exercises/044-static_methods/test.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | from app import MathOperations 3 | 4 | @pytest.mark.it("The 'MathOperations' class should exist") 5 | def test_math_operations_class_exists(): 6 | try: 7 | assert MathOperations 8 | except AttributeError: 9 | raise AttributeError("The class 'MathOperations' should exist in app.py") 10 | 11 | @pytest.mark.it("The MathOperations class includes the 'add_numbers' static method") 12 | def test_math_operations_has_add_numbers_static_method(): 13 | assert hasattr(MathOperations, "add_numbers") 14 | 15 | @pytest.mark.it("The 'add_numbers' static method should return the expected sum") 16 | def test_add_numbers_static_method_returns_expected_sum(): 17 | result = MathOperations.add_numbers(5, 7) 18 | assert result == 12 19 | 20 | @pytest.mark.it("The 'add_numbers' static method should return the expected sum. Testing with different values") 21 | def test_add_numbers_static_method_returns_expected_sum_for_different_values(): 22 | result = MathOperations.add_numbers(10, 20) 23 | assert result == 30 24 | -------------------------------------------------------------------------------- /exercises/045-class_methods/README.es.md: -------------------------------------------------------------------------------- 1 | # `045` class methods 2 | 3 | Un **método de clase** es un método que está vinculado a la clase y no a la instancia de la clase. Toma la clase misma como su primer parámetro, a menudo llamado "cls". Los métodos de clase se definen utilizando el decorador @classmethod. 4 | 5 | La característica principal de un método de clase es que puede acceder y modificar atributos a nivel de clase, pero no puede acceder ni modificar atributos específicos de la instancia, ya que no tiene acceso a una instancia de la clase. Los métodos de clase se utilizan a menudo para tareas que involucran a la clase en sí misma en lugar de a instancias individuales. 6 | 7 | ```py 8 | class Person: 9 | total_people = 0 # Variable de clase para llevar el seguimiento del número total de personas 10 | 11 | def __init__(self, name, age): 12 | self.name = name 13 | self.age = age 14 | Person.total_people += 1 # Incrementa el recuento de total_people por cada nueva instancia 15 | 16 | @classmethod 17 | def get_total_people(cls): 18 | return cls.total_people 19 | 20 | # Creando instancias de Person 21 | person1 = Person("Alice", 25) 22 | person2 = Person("Bob", 16) 23 | 24 | # Usando el class method para obtener el número total de personas 25 | total_people = Person.get_total_people() 26 | print(f"Total People: {total_people}") 27 | ``` 28 | 29 | En este ejemplo: 30 | 31 | + El método de clase `get_total_people` devuelve el número total de personas creadas (instancias de la clase Persona). 32 | 33 | ## 📝 Instrucciones: 34 | 35 | 1. Crea una clase llamada `MathOperations`. 36 | 37 | 2. Dentro de la clase, define lo siguiente: 38 | 39 | + Una variable de clase llamada `pi` con un valor de `3.14159`. 40 | + Un método de clase llamado `calculate_circle_area` que tome un radio como parámetro y devuelva el área de un círculo utilizando la fórmula: `area = π × radio²`. 41 | 42 | 3. Utiliza el método de clase `calculate_circle_area` para calcular el área de un círculo con un radio de 5. 43 | 44 | 4. Imprime el resultado. (No es necesario crear ninguna instancia) 45 | 46 | ## 📎 Ejemplo de entrada: 47 | 48 | ```py 49 | circle_area = MathOperations.calculate_circle_area(5) 50 | ``` 51 | 52 | ## 📎 Ejemplo de salida: 53 | 54 | ```py 55 | # Circle Area: 78.53975 56 | ``` 57 | 58 | ## 💡 Pistas: 59 | 60 | + Recuerda, para crear un método de clase, utiliza el decorador `@classmethod` encima de la definición del método. 61 | 62 | + ¿Atascado? Si tienes alguna pregunta, ponte en contacto con tus profesores, compañeros de clase, o utiliza el canal de Slack `#public-support-full-stack` para aclarar tus dudas. 63 | 64 | + Cuando termines con este ejercicio, añade el `@staticmethod` del ejercicio anterior a tu clase y tómate tu tiempo para entender sus diferencias y el porqué de cada uno. -------------------------------------------------------------------------------- /exercises/045-class_methods/README.md: -------------------------------------------------------------------------------- 1 | # `045` class methods 2 | 3 | A **class method** is a method that is bound to the class and not the instance of the class. It takes the class itself as its first parameter, often named "cls". Class methods are defined using the @classmethod decorator. 4 | 5 | The primary characteristic of a class method is that it can access and modify class-level attributes, but it cannot access or modify instance-specific attributes since it doesn't have access to an instance of the class. Class methods are often used for tasks that involve the class itself rather than individual instances. 6 | 7 | ```py 8 | class Person: 9 | total_people = 0 # Class variable to keep track of the total number of people 10 | 11 | def __init__(self, name, age): 12 | self.name = name 13 | self.age = age 14 | Person.total_people += 1 # Increment the total_people count for each new instance 15 | 16 | @classmethod 17 | def get_total_people(cls): 18 | return cls.total_people 19 | 20 | # Creating instances of Person 21 | person1 = Person("Alice", 25) 22 | person2 = Person("Bob", 16) 23 | 24 | # Using the class method to get the total number of people 25 | total_people = Person.get_total_people() 26 | print(f"Total People: {total_people}") 27 | ``` 28 | 29 | In this example: 30 | 31 | + The class method `get_total_people` returns the total number of people created (instances of the Person class). 32 | 33 | ## 📝 Instructions: 34 | 35 | 1. Create a class called `MathOperations`. 36 | 37 | 2. Inside the class, define the following: 38 | 39 | + A class variable named `pi` with a value of `3.14159`. 40 | + A class method named `calculate_circle_area` that takes a radius as a parameter and returns the area of a circle using the formula: `area = π × radius²` 41 | 42 | 3. Use the class method `calculate_circle_area` to calculate the area of a circle with a radius of 5. 43 | 44 | 4. Print the result. (No need to create any instance) 45 | 46 | ## 📎 Example input: 47 | 48 | ```py 49 | circle_area = MathOperations.calculate_circle_area(5) 50 | ``` 51 | 52 | ## 📎 Example output: 53 | 54 | ```py 55 | # Circle Area: 78.53975 56 | ``` 57 | 58 | 59 | ## 💡 Hints: 60 | 61 | + Remember, to create a class method, use the `@classmethod` decorator above the method definition. 62 | 63 | + Stuck? if you have any questions, reach out to your teachers, classmates, or use the Slack `#public-support-full-stack` channel to clear your doubts. 64 | 65 | + When you finish this exercise, add the `@staticmethod` from the previous exercise to your class and take your time to understand their differences and the reasons behind each one. -------------------------------------------------------------------------------- /exercises/045-class_methods/app.py: -------------------------------------------------------------------------------- 1 | # Your code here 2 | 3 | -------------------------------------------------------------------------------- /exercises/045-class_methods/solution.hide.py: -------------------------------------------------------------------------------- 1 | # Your code here 2 | 3 | class MathOperations: 4 | pi = 3.14159 5 | 6 | @classmethod 7 | def calculate_circle_area(cls, radius): 8 | area = cls.pi * radius ** 2 9 | return area 10 | 11 | circle_area = MathOperations.calculate_circle_area(5) 12 | 13 | print(f"Circle Area: {circle_area}") -------------------------------------------------------------------------------- /exercises/045-class_methods/test.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | from app import MathOperations 3 | 4 | @pytest.mark.it("The 'MathOperations' class should exist") 5 | def test_math_operations_class_exists(): 6 | try: 7 | assert MathOperations 8 | except AttributeError: 9 | raise AttributeError("The class 'MathOperations' should exist in app.py") 10 | 11 | 12 | @pytest.mark.it("The MathOperations class includes the 'calculate_circle_area' class method") 13 | def test_math_operations_has_calculate_circle_area_class_method(): 14 | assert hasattr(MathOperations, "calculate_circle_area") 15 | 16 | 17 | @pytest.mark.it("The 'calculate_circle_area' class method should return the expected circle area") 18 | def test_calculate_circle_area_class_method_returns_expected_area(): 19 | result = MathOperations.calculate_circle_area(5) 20 | assert result == 78.53975 21 | 22 | @pytest.mark.it("The 'calculate_circle_area' class method should return the expected circle area. Testing with different values") 23 | def test_calculate_circle_area_class_method_returns_expected_area_for_radius_10(): 24 | result = MathOperations.calculate_circle_area(10) 25 | assert result == 314.159 26 | -------------------------------------------------------------------------------- /learn.json: -------------------------------------------------------------------------------- 1 | { 2 | "language": "python3", 3 | "slug": "practice-python", 4 | "title": { 5 | "us": "Master Python by practice (interactive)", 6 | "es": "Domina Python Practicando (interactivo)" 7 | }, 8 | "repository": "https://github.com/4GeeksAcademy/master-python-programming-exercises", 9 | "preview": "https://github.com/4GeeksAcademy/master-python-programming-exercises/blob/master/preview.gif?raw=true", 10 | "description": { 11 | "us": "Practice your Python programming skills with this interactive and auto-graded set of exercises.", 12 | "es": "Practica tus habilidades de python con esta serie de ejercicios interactivos y auto-evaluados." 13 | }, 14 | "duration": 10, 15 | "difficulty": "easy", 16 | "videoSolutions": false, 17 | "projectType": "tutorial", 18 | "bugsLink": "https://github.com/learnpack/learnpack/issues/new", 19 | "graded": true, 20 | 21 | "editor": { 22 | "version": "5.0" 23 | }, 24 | "telemetry": { 25 | "batch": "https://breathecode.herokuapp.com/v1/assignment/me/telemetry?asset_id=146" 26 | } 27 | 28 | } 29 | -------------------------------------------------------------------------------- /preview.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/4GeeksAcademy/master-python-programming-exercises/c5d0bdcb7da8f3b57c03268b301dd8760dd9506a/preview.gif --------------------------------------------------------------------------------