Compare commits

...

270 Commits

Author SHA1 Message Date
92e473fdfe Add script to README 2025-11-08 22:44:22 +01:00
6e97f2bea1 Add script secret_santa.py 2025-11-08 22:31:34 +01:00
fa1ee4dd64 feat: add local date in docker-compose files 2025-07-12 17:10:20 +02:00
b9884d6560 Comments in docker-compose 2025-05-22 22:57:42 +02:00
9245dbb9af Add compose in clima_bot 2025-05-22 21:07:19 +02:00
2c4f14a886 Update mareas_bot 2025-02-21 21:31:58 +01:00
1fa360a109 mareas_bot: Fix errors. Update dependencies. Add enhancements 2025-02-19 23:27:15 +01:00
a2badd511d Fusionar feature/tablamareasbot en main 2025-02-19 21:24:50 +01:00
68b9bf32a3 Add rubiks cube solver 2024-09-01 21:48:24 +02:00
21c7e1e6c6 Add enhanced urlf4ck3r 2024-09-01 19:18:39 +02:00
dc9e81f06e Update Ollama bot 2024-08-18 21:15:33 +02:00
dd48618093 Update Ollama bot 2024-08-18 20:18:59 +02:00
3e47d5a7ee Add Ollama bot 2024-08-18 20:16:34 +02:00
d59e31205b Update chatgpt bot 2024-08-18 19:43:44 +02:00
e2767e99af Update chatgpt bot 2024-08-17 21:11:58 +02:00
65468e4115 Add chatgpt bot 2024-08-17 21:08:24 +02:00
4f2264748e Update README 2024-08-15 19:43:39 +02:00
a73e8a0222 Update diagrams test README 2024-08-13 01:46:47 +02:00
84a2519f6c Add diagrams test 2024-08-13 01:43:53 +02:00
88a26dae34 Update .gitignore 2024-08-13 01:30:37 +02:00
b672828792 Add sonarqube test 2024-08-09 02:22:44 +02:00
40fad6bae8 Add prometheus_grafana test 2024-08-09 01:20:19 +02:00
17a7e04180 Update README infra 2024-08-08 00:03:17 +02:00
6cb79e3418 Add structure prometheus_grafana & sonarqube 2024-08-08 00:01:27 +02:00
28f9bb389d Add kafka test 2024-08-07 23:59:44 +02:00
f525beaf11 Update .gitignore 2024-08-07 23:59:06 +02:00
4756d756ac Update elastic stack test 2024-08-07 19:56:05 +02:00
89959d29ee Update rabbitmq test 2024-08-06 22:05:20 +02:00
898da84dc3 Update rabbitmq test 2024-08-05 23:37:04 +02:00
bba89794a2 Update .gitignore 2024-08-05 23:36:38 +02:00
78552c227a Update rabbitmq test 2024-08-04 20:56:58 +02:00
9a60b44822 Update .gitignore 2024-08-04 20:55:49 +02:00
e856e99ac3 Update READMEs 2024-08-02 20:10:03 +02:00
7102b86e6e Update README catch-all 2024-08-02 20:07:49 +02:00
50513ff393 Add rabbitmq test 2024-07-31 23:27:53 +02:00
0daba91bbb Update README infra test 2024-07-31 13:38:57 +02:00
a7cefe06d0 Add rabbitmq test 2024-07-30 23:55:17 +02:00
ecd77967a0 Add movies trivial Bot for Telegram 2024-07-30 00:43:20 +02:00
be39d5b1d3 Re-structure infra folder 2024-07-22 21:09:54 +02:00
d7640c2a52 Update movie_bot 2024-07-22 20:55:34 +02:00
2b946f3327 Update README Bots Telegram 2024-07-17 21:17:07 +02:00
5ff0fa4f2a Update movie Bot for Telegram 2024-07-17 18:44:16 +02:00
a421d3b292 Add movie Bot for Telegram 2024-07-17 01:10:27 +02:00
84e3344d49 Add rss Bot for Telegram 2024-07-16 00:48:20 +02:00
56ac284176 Update .gitignore 2024-07-15 23:59:31 +02:00
94e6ca1027 Update README 2024-07-15 23:41:28 +02:00
819aaaa1f5 Add Weather Bot for Telegram 2024-07-14 19:20:40 +02:00
d8ca020c98 Update README 2024-07-13 14:20:03 +02:00
fbecbbf0a1 Add Translator Bot for Telegram 2024-07-11 02:54:47 +02:00
5821636a01 Update Bots Telegram 2024-07-10 01:06:53 +02:00
62d0ec78b5 Add bots telegram 2024-07-10 01:03:15 +02:00
71d0a3c4d8 Add new exercise 2024-06-16 18:00:16 +02:00
d7c1cee2a8 Add link shortener in README 2024-02-27 23:29:08 +01:00
c1c5883a56 Add link shortener 2024-02-27 23:20:35 +01:00
485d16e930 Fix errors 2024-02-20 19:12:25 +01:00
35727e1664 Update README 2024-02-19 23:52:29 +01:00
a55a297cdb Add weather script 2024-02-19 23:47:25 +01:00
69389a8940 Update versions 2024-02-13 20:26:34 +01:00
3d5486414f Update README 2024-02-04 01:16:11 +01:00
d7252c6782 Update forwardshell script 2024-02-03 12:28:27 +01:00
d4c5d8a50f wip 2024-02-03 12:27:47 +01:00
5d7e3302c5 wip 2024-02-02 23:02:37 +01:00
0d95645a93 Delete backdoor.exe 2024-02-01 19:19:01 +01:00
3704f6c61e Update backdoor & listener - C2 2024-02-01 19:18:06 +01:00
d505f6ee23 Remove malware.exe 2024-02-01 19:17:06 +01:00
bcb3977c07 wip 2024-02-01 01:27:14 +01:00
6ae9c26e65 Add backdoor 2024-02-01 01:26:44 +01:00
d1a05d481b Update malware 2024-02-01 01:26:21 +01:00
21313f990b Update keylogger 2024-02-01 01:26:01 +01:00
213a859a7d Add malware 2024-01-31 20:29:22 +01:00
352889e2ba Add keylogger 2024-01-30 22:49:34 +01:00
2de0131f95 Add traffic hijacking 2024-01-30 18:42:58 +01:00
f7043ed2ae Add dns spoofer 2024-01-30 18:42:35 +01:00
d828243927 Add intercept packets script 2024-01-30 18:42:12 +01:00
04be4f610d Add images sniffer 2024-01-29 19:29:24 +01:00
ace46c757a Add https sniffers with mitmdump 2024-01-29 19:29:03 +01:00
4abbfdf261 Add sniffer scapy 2024-01-29 19:28:10 +01:00
92ed9c3beb Update arp spoofer & dns sniffer 2024-01-29 19:27:46 +01:00
c86c4f8b21 Update .gitignore 2024-01-29 19:27:00 +01:00
4847e32f04 Add DNS sniffer 2024-01-28 23:41:08 +01:00
371cd18bf0 Add arp spoof 2024-01-28 22:35:39 +01:00
cb7b2c2e13 Update network scan 2024-01-28 20:53:14 +01:00
4890661532 Update network scan & add arp scan 2024-01-28 19:38:36 +01:00
222649cd8d Add network scan 2024-01-28 16:06:28 +01:00
8f2913d463 Update README 2024-01-26 19:42:05 +01:00
7f601e84a7 Add mac changer 2024-01-26 19:40:27 +01:00
7dddcfaa28 Add port scan 2024-01-26 18:13:36 +01:00
386c544294 Update READMEç 2024-01-25 23:16:13 +01:00
9801b42111 Update README 2024-01-25 23:13:01 +01:00
5be31fd800 Update README 2024-01-25 23:11:44 +01:00
80e7e4a21c Update .gitignore 2024-01-25 23:09:25 +01:00
b8187724d2 Update chat project 2024-01-25 23:06:43 +01:00
c0b6b881e4 Add chat project 2024-01-25 22:26:39 +01:00
bd197dc519 Add calculator project 2024-01-24 18:45:39 +01:00
81e279e30a Add notepad project 2024-01-24 18:45:08 +01:00
23805c8241 Add library exercises 2024-01-24 18:44:22 +01:00
cf745e8c8d Add library exercises 2024-01-23 21:21:18 +01:00
700c489428 Add library exercises 2024-01-19 21:34:36 +01:00
658f94c62b Add library exercises 2024-01-17 20:50:25 +01:00
d15f5b4eb6 Add libraries exercises 2024-01-17 19:25:30 +01:00
062908b4ee Update README 2024-01-16 22:33:36 +01:00
72ccded05d Update requests exercise 2024-01-14 00:15:52 +01:00
17d758d75b Update descifrador 2024-01-13 20:37:11 +01:00
9ad2161b99 Add librerias exercices 2024-01-13 20:31:41 +01:00
36973a9662 Add wargame decode 2024-01-13 16:58:21 +01:00
8109c2fe30 Update Python Ofensivo - Más ejercicios con conexiones socket 2024-01-11 23:08:41 +01:00
f09fa0cbf5 Update Python Ofensivo - Pruebas de conexión UDP con la librería socket 2024-01-11 21:43:05 +01:00
ec29b5cde0 Update Python Ofensivo - Pruebas de conexión con la librería socket 2024-01-11 20:26:58 +01:00
653e96cc2b Update Python Ofensivo - Proyecto gestor de notas 2024-01-11 20:26:18 +01:00
3ce3338795 Update Python Ofensivo - validador de correo con regex 2024-01-11 20:25:12 +01:00
818ec91771 Update Python Ofensivo 2024-01-10 23:29:44 +01:00
bb39d2366f Update Python Ofensivo 2024-01-10 22:55:31 +01:00
1f8a74e791 Update Python Ofensivo 2024-01-09 23:34:35 +01:00
661b027ccc Update Python Ofensivo 2024-01-09 22:57:42 +01:00
7c2ccb390c Update Python Ofensivo 2024-01-08 22:36:16 +01:00
d49859c627 Update Python Ofensivo 2023-12-29 07:05:48 +01:00
159d9490a4 Update Python Ofensivo 2023-12-29 05:35:02 +01:00
4c142e7432 Update Python Ofensivo 2023-12-28 08:25:43 +01:00
e300dee83f Update Python Ofensivo 2023-12-26 23:56:20 +01:00
490afce41f Update Python Ofensivo 2023-12-25 21:16:48 +01:00
ab95e6f805 Update Python Ofensivo 2023-12-25 10:54:18 +01:00
8896ac39c2 Update Python Ofensivo 2023-12-24 09:06:20 +01:00
3402445513 Update Python Ofensivo 2023-12-24 08:54:53 +01:00
54f7024e20 Update Python Ofensivo 2023-12-21 20:06:55 +01:00
51ed9bc844 Update Python Ofensivo 2023-12-20 20:38:59 +01:00
9d7531b0f1 Update Python Ofensivo 2023-12-20 18:51:37 +01:00
be1177090b Update Python Ofensivo 2023-12-19 23:59:04 +01:00
a307064326 Update Python Ofensivo 2023-12-17 16:00:46 +01:00
85549ac613 Update Python Ofensivo 2023-12-14 21:55:17 +01:00
086b1ca614 Add course Python ofensivo
Signed-off-by: Manuel Vergara <manuel@vergaracarmona.es>
2023-12-13 23:07:30 +01:00
5b62da6cf0 Update README
Signed-off-by: Manuel Vergara <manuel@vergaracarmona.es>
2023-12-13 17:54:23 +01:00
Manuel Vergara
af9e0b66d9 Merge pull request #1 from manuelver/dependabot/pip/30-days-of-python/26_Desarrollo_web_en_Python/web/werkzeug-3.0.1
Bump werkzeug from 3.0.0 to 3.0.1 in /30-days-of-python/26_Desarrollo_web_en_Python/web
2023-10-31 23:03:55 +01:00
dependabot[bot]
219078c375 Bump werkzeug in /30-days-of-python/26_Desarrollo_web_en_Python/web
Bumps [werkzeug](https://github.com/pallets/werkzeug) from 3.0.0 to 3.0.1.
- [Release notes](https://github.com/pallets/werkzeug/releases)
- [Changelog](https://github.com/pallets/werkzeug/blob/main/CHANGES.rst)
- [Commits](https://github.com/pallets/werkzeug/compare/3.0.0...3.0.1)

---
updated-dependencies:
- dependency-name: werkzeug
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-10-31 21:53:54 +00:00
db00df2e56 Update README
Signed-off-by: Manuel Vergara <manuel@vergaracarmona.es>
2023-10-11 00:12:44 +02:00
a320317a9e Add exercises 28
Signed-off-by: Manuel Vergara <manuel@vergaracarmona.es>
2023-10-10 23:07:29 +02:00
61d38a9b7b Update exercises 27
Signed-off-by: Manuel Vergara <manuel@vergaracarmona.es>
2023-10-10 00:09:52 +02:00
a0d26af9ed Add exercises 27
Signed-off-by: Manuel Vergara <manuel@vergaracarmona.es>
2023-10-10 00:05:16 +02:00
6fb5471334 Update README
Signed-off-by: Manuel Vergara <manuel@vergaracarmona.es>
2023-10-09 20:49:10 +02:00
08d20fee61 Add exercises 26
Signed-off-by: Manuel Vergara <manuel@vergaracarmona.es>
2023-10-09 00:00:03 +02:00
d8426a91d9 Add exercises 25
Signed-off-by: Manuel Vergara <manuel@vergaracarmona.es>
2023-10-08 22:30:44 +02:00
398494e2f5 Add exercises 24 part 2
Signed-off-by: Manuel Vergara <manuel@vergaracarmona.es>
2023-10-08 22:00:31 +02:00
d6a26ea924 Add exercises 24 part 1
Signed-off-by: Manuel Vergara <manuel@vergaracarmona.es>
2023-10-08 21:51:12 +02:00
40d20c3bcf Update README
Signed-off-by: Manuel Vergara <manuel@vergaracarmona.es>
2023-10-06 22:30:44 +02:00
8afad81939 Update README
Signed-off-by: Manuel Vergara <manuel@vergaracarmona.es>
2023-10-06 22:19:28 +02:00
2ff37fdb2b Update README
Signed-off-by: Manuel Vergara <manuel@vergaracarmona.es>
2023-10-06 22:17:06 +02:00
a8c1199c90 Add exercises 23
Signed-off-by: Manuel Vergara <manuel@vergaracarmona.es>
2023-10-05 02:23:51 +02:00
94c89522d1 Add exercises 21 - Solved 3
Signed-off-by: Manuel Vergara <manuel@vergaracarmona.es>
2023-10-05 02:04:06 +02:00
7b2cd6c376 Add exercises 21 - Solved 2
Signed-off-by: Manuel Vergara <manuel@vergaracarmona.es>
2023-10-05 00:01:26 +02:00
6677000878 Add exercises 21 - Solved 1
Signed-off-by: Manuel Vergara <manuel@vergaracarmona.es>
2023-10-04 23:17:38 +02:00
2cd9b703b2 Add exercises 21 - Not solved
Signed-off-by: Manuel Vergara <manuel@vergaracarmona.es>
2023-10-03 23:50:51 +02:00
d34da87ee0 Add exercises 21
Signed-off-by: Manuel Vergara <manuel@vergaracarmona.es>
2023-10-02 00:03:56 +02:00
8bb0639340 Add exercises 20
Signed-off-by: Manuel Vergara <manuel@vergaracarmona.es>
2023-10-01 23:50:57 +02:00
daabecd4a1 Update exercises 19
Signed-off-by: Manuel Vergara <manuel@vergaracarmona.es>
2023-10-01 00:45:52 +02:00
b86c542424 Add exercises 19
Signed-off-by: Manuel Vergara <manuel@vergaracarmona.es>
2023-10-01 00:39:09 +02:00
7f6426e0ee Update exercises 18
Signed-off-by: Manuel Vergara <manuel@vergaracarmona.es>
2023-09-30 22:26:15 +02:00
f391b1b42a Add exercises 18
Signed-off-by: Manuel Vergara <manuel@vergaracarmona.es>
2023-09-30 21:38:24 +02:00
58aac99650 Update README exercises 10
Signed-off-by: Manuel Vergara <manuel@vergaracarmona.es>
2023-09-29 19:50:27 +02:00
9df7a5bfbe Add exercises 17
Signed-off-by: Manuel Vergara <manuel@vergaracarmona.es>
2023-09-29 00:23:10 +02:00
d191a1a03d Add exercises 16
Signed-off-by: Manuel Vergara <manuel@vergaracarmona.es>
2023-09-29 00:16:16 +02:00
3da7ec4195 Add exercises 15
Signed-off-by: Manuel Vergara <manuel@vergaracarmona.es>
2023-09-29 00:00:35 +02:00
e1121c9826 Add exercises 14
Signed-off-by: Manuel Vergara <manuel@vergaracarmona.es>
2023-09-28 00:02:42 +02:00
b89cfe618a Add exercises 13
Signed-off-by: Manuel Vergara <manuel@vergaracarmona.es>
2023-09-27 22:39:30 +02:00
b833f45c56 Update README.md 2023-09-27 19:56:28 +00:00
d35044c16b Add cool gif
Signed-off-by: Manuel Vergara <manuel@vergaracarmona.es>
2023-09-27 01:38:02 +02:00
19f22f039a Update structure
Signed-off-by: Manuel Vergara <manuel@vergaracarmona.es>
2023-09-27 01:21:16 +02:00
13f01de361 Add exercises 12
Signed-off-by: Manuel Vergara <manuel@vergaracarmona.es>
2023-09-26 19:44:50 +02:00
acfcd590da Add exercises 11
Signed-off-by: Manuel Vergara <manuel@vergaracarmona.es>
2023-09-24 22:00:23 +02:00
741f07dd9d Add exercises 10
Signed-off-by: Manuel Vergara <manuel@vergaracarmona.es>
2023-09-23 01:06:12 +02:00
7ea10164ef Add exercises 09
Signed-off-by: Manuel Vergara <manuel@vergaracarmona.es>
2023-09-22 23:51:05 +02:00
f27f538aaa Update README
Signed-off-by: Manuel Vergara <manuel@vergaracarmona.es>
2023-09-22 01:11:03 +02:00
14d9bfd01f Update catch-all
Signed-off-by: Manuel Vergara <manuel@vergaracarmona.es>
2023-09-21 23:56:40 +02:00
ae19285fb6 Update catch-all
Signed-off-by: Manuel Vergara <manuel@vergaracarmona.es>
2023-09-21 23:52:00 +02:00
6f8fa5ee62 Update README & add catch-all
Signed-off-by: Manuel Vergara <manuel@vergaracarmona.es>
2023-09-21 23:46:25 +02:00
897c383904 Add exercises 08
Signed-off-by: Manuel Vergara <manuel@vergaracarmona.es>
2023-09-21 22:24:14 +02:00
d01df21cce Add exercises 07
Signed-off-by: Manuel Vergara <manuel@vergaracarmona.es>
2023-09-21 00:11:54 +02:00
064d02a9b3 Add exercises 06
Signed-off-by: Manuel Vergara <manuel@vergaracarmona.es>
2023-09-20 18:27:48 +02:00
afbbaad4e6 Add exercises 05
Signed-off-by: Manuel Vergara <manuel@vergaracarmona.es>
2023-09-20 00:15:36 +02:00
20ecef1adb Add exercises 04
Signed-off-by: Manuel Vergara <manuel@vergaracarmona.es>
2023-09-19 00:03:54 +02:00
4e95ba5dca Add exercises 03
Signed-off-by: Manuel Vergara <manuel@vergaracarmona.es>
2023-09-18 23:36:43 +02:00
0dad4e672e Add exercises 02
Signed-off-by: Manuel Vergara <manuel@vergaracarmona.es>
2023-09-18 23:08:56 +02:00
5508c0381c Add exercises 01
Signed-off-by: Manuel Vergara <manuel@vergaracarmona.es>
2023-09-18 23:00:44 +02:00
3d867aed80 Add exercise of new course 30-days-of-python
Signed-off-by: Manuel Vergara <manuel@vergaracarmona.es>
2023-09-18 01:00:26 +02:00
f04e8db31f Update README, add new course 30-days-of-python
Signed-off-by: Manuel Vergara <manuel@vergaracarmona.es>
2023-09-17 22:39:56 +02:00
2f487dd086 Update README python-total
Signed-off-by: Manuel Vergara <manuel@vergaracarmona.es>
2023-09-17 22:39:19 +02:00
c46313157d Update README scripts-hacking
Signed-off-by: Manuel Vergara <manuel@vergaracarmona.es>
2023-06-15 20:30:11 +02:00
52c07acb0a Update README
Signed-off-by: Manuel Vergara <manuel@vergaracarmona.es>
2023-06-11 18:49:10 +02:00
42a02f09e9 Update README
Signed-off-by: Manuel Vergara <manuel@vergaracarmona.es>
2023-06-10 22:59:27 +02:00
3769dde16e Update python-chatGPT course - Add index
Signed-off-by: Manuel Vergara <manuel@vergaracarmona.es>
2023-06-10 22:57:48 +02:00
1b5a79be68 Update python-chatGPT course
Signed-off-by: Manuel Vergara <manuel@vergaracarmona.es>
2023-06-10 22:49:39 +02:00
91154fa094 Update python-chatGPT course
Signed-off-by: Manuel Vergara <manuel@vergaracarmona.es>
2023-06-10 22:11:57 +02:00
ce1df90cb1 Update python-chatGPT course
Signed-off-by: Manuel Vergara <manuel@vergaracarmona.es>
2023-06-10 18:42:54 +02:00
5b40a76d6b Update python-chatGPT course
Signed-off-by: Manuel Vergara <manuel@vergaracarmona.es>
2023-06-10 18:41:05 +02:00
c3fdcdec37 Update python-chatGPT course
Signed-off-by: Manuel Vergara <manuel@vergaracarmona.es>
2023-06-10 17:48:19 +02:00
bd11fc17e2 Update python-chatGPT course
Signed-off-by: Manuel Vergara <manuel@vergaracarmona.es>
2023-06-10 14:24:18 +02:00
41f6f3af32 Add exercise 10 by script-hacking course
Signed-off-by: Manuel Vergara <manuel@vergaracarmona.es>
2023-06-09 00:19:10 +02:00
a9d3a139be Add exercise 9 by script-hacking course
Signed-off-by: Manuel Vergara <manuel@vergaracarmona.es>
2023-06-08 20:27:35 +02:00
e4ac2ba3b4 Add exercise 8 by script-hacking course
Signed-off-by: Manuel Vergara <manuel@vergaracarmona.es>
2023-06-08 20:27:14 +02:00
bae9018e6f Add exercise 7 by script-hacking course
Signed-off-by: Manuel Vergara <manuel@vergaracarmona.es>
2023-06-06 21:06:43 +02:00
56e63522ac Add exercise 5 by script-hacking course
Signed-off-by: Manuel Vergara <manuel@vergaracarmona.es>
2023-06-06 20:19:58 +02:00
057053bd62 Add exercise 4 by script-hacking course
Signed-off-by: Manuel Vergara <manuel@vergaracarmona.es>
2023-06-06 20:04:43 +02:00
e0c73bda48 Add exercise 3 by script-hacking course
Signed-off-by: Manuel Vergara <manuel@vergaracarmona.es>
2023-06-06 19:44:44 +02:00
9af7fa58d9 Add exercise 2 by script-hacking course
Signed-off-by: Manuel Vergara <manuel@vergaracarmona.es>
2023-06-06 17:33:28 +02:00
5ac64d1897 Add exercise 1 by script-hacking course
Signed-off-by: Manuel Vergara <manuel@vergaracarmona.es>
2023-06-06 17:18:11 +02:00
71f53b470b Update python-chatGPT course
Signed-off-by: Manuel Vergara <manuel@vergaracarmona.es>
2023-06-05 22:13:37 +02:00
8eccfe3a27 Add Python-chatGPT course - 3.2
Signed-off-by: Manuel Vergara <manuel@vergaracarmona.es>
2023-06-02 17:58:07 +02:00
d829239f8f Update course READMEs
Signed-off-by: Manuel Vergara <manuel@vergaracarmona.es>
2023-05-30 23:00:11 +02:00
4366555821 Update README
Signed-off-by: Manuel Vergara <manuel@vergaracarmona.es>
2023-05-30 22:49:44 +02:00
f45e948096 Update README
Signed-off-by: Manuel Vergara <manuel@vergaracarmona.es>
2023-05-30 22:48:37 +02:00
da96ca4c0a Add python-chatgpt
Signed-off-by: Manuel Vergara <manuel@vergaracarmona.es>
2023-05-30 22:41:27 +02:00
7e0ac99631 Add python-chatgpt
Signed-off-by: Manuel Vergara <manuel@vergaracarmona.es>
2023-05-30 22:40:31 +02:00
09b13abe14 Add python-chatgpt
Signed-off-by: Manuel Vergara <manuel@vergaracarmona.es>
2023-05-29 23:25:00 +02:00
fc713b3fd0 Update scripts-hacking-etico README
Signed-off-by: Manuel Vergara <manuel@vergaracarmona.es>
2023-05-29 22:14:20 +02:00
1f7a4ff2d5 Update README
Signed-off-by: Manuel Vergara <manuel@vergaracarmona.es>
2023-05-29 20:25:08 +02:00
47121b2de7 Update README and structure
Signed-off-by: Manuel Vergara <manuel@vergaracarmona.es>
2023-05-28 00:57:11 +02:00
d3d5f1ee0d Update python-total README
Signed-off-by: Manuel Vergara <manuel@vergaracarmona.es>
2023-05-28 00:50:12 +02:00
6fc1cc975a Update day 16
Signed-off-by: Manuel Vergara <manuel@vergaracarmona.es>
2023-05-28 00:34:31 +02:00
22ef92d980 Update day 16
Signed-off-by: Manuel Vergara <manuel@vergaracarmona.es>
2023-05-27 23:49:12 +02:00
c809ab1dac Update day 16
Signed-off-by: Manuel Vergara <manuel@vergaracarmona.es>
2023-05-27 23:18:27 +02:00
f4e5dfcf3c Update day 16
Signed-off-by: Manuel Vergara <manuel@vergaracarmona.es>
2023-05-27 20:01:12 +02:00
029f2e18b3 Update day 16
Signed-off-by: Manuel Vergara <manuel@vergaracarmona.es>
2023-05-27 18:32:29 +02:00
1126df30af Update day 16
Signed-off-by: Manuel Vergara <manuel@vergaracarmona.es>
2023-05-27 18:08:22 +02:00
376742e0a3 Update day 16
Signed-off-by: Manuel Vergara <manuel@vergaracarmona.es>
2023-05-27 18:07:33 +02:00
374f2e5276 Update day 16
Signed-off-by: Manuel Vergara <manuel@vergaracarmona.es>
2023-05-27 17:33:50 +02:00
63ea50d53c Update day 16
Signed-off-by: Manuel Vergara <manuel@vergaracarmona.es>
2023-05-25 21:42:51 +02:00
20b227ce65 Update day 17
Signed-off-by: Manuel Vergara <manuel@vergaracarmona.es>
2023-05-24 01:05:01 +02:00
fc3c917e4d Update day 16
Signed-off-by: Manuel Vergara <manuel@vergaracarmona.es>
2023-05-24 00:41:03 +02:00
6d977ce83a Update day 16
Signed-off-by: Manuel Vergara <manuel@vergaracarmona.es>
2023-05-24 00:36:13 +02:00
af00070aeb Update day 16
Signed-off-by: Manuel Vergara <manuel@vergaracarmona.es>
2023-05-24 00:15:01 +02:00
741187de54 Update day 16
Signed-off-by: Manuel Vergara <manuel@vergaracarmona.es>
2023-05-23 23:55:18 +02:00
4fb899f0a3 Update day 16
Signed-off-by: Manuel Vergara <manuel@vergaracarmona.es>
2023-05-23 23:29:45 +02:00
c317b46db0 Update day 16
Signed-off-by: Manuel Vergara <manuel@vergaracarmona.es>
2023-05-22 20:52:18 +02:00
ada9cedc9b Update day 16
Signed-off-by: Manuel Vergara <manuel@vergaracarmona.es>
2023-05-22 20:35:48 +02:00
3961f0bb6c Update day 16
Signed-off-by: Manuel Vergara <manuel@vergaracarmona.es>
2023-05-22 20:26:13 +02:00
a6063da5c6 Update day 16
Signed-off-by: Manuel Vergara <manuel@vergaracarmona.es>
2023-05-21 21:59:16 +02:00
9c43d3cad5 Update day 16
Signed-off-by: Manuel Vergara <manuel@vergaracarmona.es>
2023-05-21 21:33:13 +02:00
10e318cdc5 Update day 16
Signed-off-by: Manuel Vergara <manuel@vergaracarmona.es>
2023-05-21 19:28:38 +02:00
33e2f1b72f Update day 16
Signed-off-by: Manuel Vergara <manuel@vergaracarmona.es>
2023-05-21 19:21:17 +02:00
15ae6ed3da Update day 16
Signed-off-by: Manuel Vergara <manuel@vergaracarmona.es>
2023-05-21 18:50:15 +02:00
d795c56835 Update README
Signed-off-by: Manuel Vergara <manuel@vergaracarmona.es>
2023-05-21 11:30:41 +02:00
37bdb4851f Update README
Signed-off-by: Manuel Vergara <manuel@vergaracarmona.es>
2023-05-21 11:28:40 +02:00
e5bacedf63 Update day 16
Signed-off-by: Manuel Vergara <manuel@vergaracarmona.es>
2023-05-20 22:42:45 +02:00
3c14694026 Update .gitignore
Signed-off-by: Manuel Vergara <manuel@vergaracarmona.es>
2023-05-20 20:33:16 +02:00
0d3e1195c2 Update READMEs
Signed-off-by: Manuel Vergara <manuel@vergaracarmona.es>
2023-05-20 11:55:45 +02:00
e7c0f3dd1e Update READMEs
Signed-off-by: Manuel Vergara <manuel@vergaracarmona.es>
2023-05-20 11:06:09 +02:00
b242fafe50 Update README day 17
Signed-off-by: Manuel Vergara <manuel@vergaracarmona.es>
2023-05-20 11:02:35 +02:00
ec86e863a9 Update README day 15
Signed-off-by: Manuel Vergara <manuel@vergaracarmona.es>
2023-05-20 10:51:49 +02:00
3366f8edad Update README day 14
Signed-off-by: Manuel Vergara <manuel@vergaracarmona.es>
2023-05-20 10:45:44 +02:00
75c9a61975 Update README day 13
Signed-off-by: Manuel Vergara <manuel@vergaracarmona.es>
2023-05-20 10:39:36 +02:00
4b5eb62497 Update README day 12
Signed-off-by: Manuel Vergara <manuel@vergaracarmona.es>
2023-05-20 10:29:10 +02:00
428e4a0400 Update README day 11
Signed-off-by: Manuel Vergara <manuel@vergaracarmona.es>
2023-05-20 10:26:31 +02:00
4993ea616a Update README day 10
Signed-off-by: Manuel Vergara <manuel@vergaracarmona.es>
2023-05-20 10:19:58 +02:00
5f8252020c Update README
Signed-off-by: Manuel Vergara <manuel@vergaracarmona.es>
2023-05-20 10:01:22 +02:00
6795e61a82 Update README
Signed-off-by: Manuel Vergara <manuel@vergaracarmona.es>
2023-05-20 09:59:15 +02:00
125f96030a Update README
Signed-off-by: Manuel Vergara <manuel@vergaracarmona.es>
2023-05-20 09:54:09 +02:00
b28640cce2 Update course READMEs
Signed-off-by: Manuel Vergara <manuel@vergaracarmona.es>
2023-05-20 09:51:38 +02:00
f4e9797c4b Restructure content and add notes from HolaMundo
Signed-off-by: Manuel Vergara <manuel@vergaracarmona.es>
2023-05-20 09:36:26 +02:00
64ed03f811 Update READMEs
Signed-off-by: Manuel Vergara <manuel@vergaracarmona.es>
2023-05-19 22:31:55 +02:00
9bc0f05cca Update README day 9
Signed-off-by: Manuel Vergara <manuel@vergaracarmona.es>
2023-05-19 22:17:38 +02:00
4bc883ee2a Update README day 8
Signed-off-by: Manuel Vergara <manuel@vergaracarmona.es>
2023-05-19 22:00:38 +02:00
878f85f335 Update README day 7
Signed-off-by: Manuel Vergara <manuel@vergaracarmona.es>
2023-05-19 21:48:59 +02:00
ef14ab0735 Update README day 6
Signed-off-by: Manuel Vergara <manuel@vergaracarmona.es>
2023-05-19 21:30:34 +02:00
9a8b10ffd7 Update README day 5
Signed-off-by: Manuel Vergara <manuel@vergaracarmona.es>
2023-05-19 21:17:17 +02:00
3b8f8881de Update README day 4
Signed-off-by: Manuel Vergara <manuel@vergaracarmona.es>
2023-05-19 19:41:19 +02:00
781fb94167 Update README day 2
Signed-off-by: Manuel Vergara <manuel@vergaracarmona.es>
2023-05-19 19:26:53 +02:00
17033302c8 Update README day 3
Signed-off-by: Manuel Vergara <manuel@vergaracarmona.es>
2023-05-19 19:21:28 +02:00
3349631608 Update README
Signed-off-by: Manuel Vergara <manuel@vergaracarmona.es>
2023-05-19 19:14:17 +02:00
b2cf53eff9 Update README dia 3 and add images
Signed-off-by: Manuel Vergara <manuel@vergaracarmona.es>
2023-05-19 19:11:30 +02:00
398463b291 Update README dia 2
Signed-off-by: Manuel Vergara <manuel@vergaracarmona.es>
2023-05-19 18:48:33 +02:00
f5b0e3793b Update README and add img
Signed-off-by: Manuel Vergara <manuel@vergaracarmona.es>
2023-05-19 18:28:11 +02:00
70c5b41c52 Add license Creative commons
Signed-off-by: Manuel Vergara <manuel@vergaracarmona.es>
2023-05-19 18:12:20 +02:00
969 changed files with 227770 additions and 734 deletions

75
.gitignore vendored
View File

@@ -73,6 +73,7 @@ instance/
docs/_build/
# PyBuilder
.pybuilder/
target/
# Jupyter Notebook
@@ -92,17 +93,45 @@ ipython_config.py
# install all needed dependencies.
#Pipfile.lock
# celery beat schedule file
# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock
# poetry
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
# This is especially recommended for binary packages to ensure reproducibility, and is more
# commonly ignored for libraries.
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
#poetry.lock
# pdm
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
#pdm.lock
# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
# in version control.
# https://pdm.fming.dev/#use-with-ide
.pdm.toml
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
__pypackages__/
# Celery stuff
celerybeat-schedule
celerybeat.pid
# SageMath parsed files
*.sage.py
# Environments
.env
*.env
.venv
env/
venv/
myenv/
ENV/
env.bak/
venv.bak/
@@ -124,3 +153,47 @@ dmypy.json
# Pyre type checker
.pyre/
# pytype static type analyzer
.pytype/
# Cython debug symbols
cython_debug/
# PyCharm
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
# and can be added to the global gitignore or merged into this file. For a more nuclear
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
#.idea/
# certificate files
# Ignore all certificates in this directory
*.pem
*.key
*.csr
# Ignore binary files of mitmproxy
mitmproxy/
# Logs
bot.log*
logs/
*.log
# Ignore database files
rss.db
# Ignore vscode settings
.vscode
# Ignore volume files
rabbitmq/
rabbitmq/*
*_data
*_data/*

View File

@@ -0,0 +1,41 @@
"""
01_introduccion.py
"""
import platform
# Comprobando la versión de Python
print("Versión de Python:", platform.python_version())
# Operaciones aritméticas
# Variables
a = 3
b = 4
# Operaciones
print("Suma:", a + b)
print("Resta:", a - b)
print("Multiplicación:", a * b)
print("Módulo:", b % a)
print("División:", b / a)
print("Potenciación:", a ** b)
print("División entera:", b // a)
# Información personal
nombre = "Romero"
apellido = "Madero"
pais = "Tu país"
print(nombre)
print(apellido)
print(pais)
print("Estoy disfrutando de 30 días de Python")
# Comprobando tipos de datos
print(type(10))
print(type(9.8))
print(type(3.14))
print(type(4 - 4j))
print(type(['Asabeneh', 'Python', 'Finlandia']))
print(type(nombre))
print(type(apellido))
print(type(pais))

View File

@@ -0,0 +1,39 @@
"""
03_introduccion.py
"""
import math
# Ejemplos de diferentes tipos de datos en Python
entero = 10
flotante = 3.14
complejo = 2 + 3j
cadena = "Hola, mundo!"
booleano = True
lista = [1, 2, 3, "cuatro"]
tupla = (1, 2, 3, "cuatro")
conjunto = {1, 2, 3, 4, 5}
diccionario = {"nombre": "Juan", "edad": 30, "ciudad": "Madrid"}
# Imprimiendo los tipos de datos
print(type(entero))
print(type(flotante))
print(type(complejo))
print(type(cadena))
print(type(booleano))
print(type(lista))
print(type(tupla))
print(type(conjunto))
print(type(diccionario))
# Cálculo de la distancia euclidiana
# Define the coordinates of the two points
x1, y1 = 2, 3
x2, y2 = 10, 8
# Calculate the Euclidean distance
distance = math.sqrt((x2 - x1)**2 + (y2 - y1)**2)
# Print the result
print("Euclidean distance:", distance)

View File

@@ -0,0 +1,48 @@
# Introducción
Documento original en inglés: [Introduction](https://github.com/Asabeneh/30-Days-Of-Python/blob/master/readme.md)
## Ejercicios
### Ejercicio: Nivel 1
- Comprueba la versión de Python que estás utilizando.
- Abre la terminal interactiva de Python y realiza las siguientes operaciones. Los operandos son 3 y 4.
- suma(+)
- resta(-)
- multiplicación(*)
- módulo(%)
- división(/)
- potenciación(**)
- operador de división entera(//)
- Escribe cadenas de texto en la terminal interactiva de Python con la siguiente información:
- Tu nombre
- Tu apellido
- Tu país
- "Estoy disfrutando de 30 días de Python".
- Comprueba los tipos de datos de los siguientes valores:
- 10
- 9.8
- 3.14
- 4 - 4j
- ['Asabeneh', 'Python', 'Finlandia']
- Tu nombre
- Tu apellido
- Tu país
[Solución](./01_introduccion.py)
### Ejercicio: Nivel 2
- Crea una carpeta llamada `day_1` dentro de la carpeta `30DaysOfPython`. Dentro de la carpeta `day_1`, crea un archivo de Python llamado `helloworld.py` y repite las preguntas 1, 2, 3 y 4. Recuerda usar `print()` cuando estés trabajando en un archivo de Python. Navega hasta el directorio donde hayas guardado tu archivo y ejecútalo.
[Solucción con truco](./hello_world.py)
### Ejercicio: Nivel 3
- Escribe un ejemplo para diferentes tipos de datos en Python, como Número (Entero, Flotante, Complejo), Cadena de texto, Booleano, Lista, Tupla, Conjunto y Diccionario.
- Encuentra la distancia euclidiana entre (2, 3) y (10, 8).
[Solución](./03_introduccion.py)
[<< INTRO](../README.md) | [Day 2 >>](../02_Variables_funciones_incorporadas/README.md)

View File

@@ -0,0 +1,9 @@
"""
02_introduccion.py
Como el ejercicio es repetitivo ejecuto desdes aquí
el fichero del ejercicio 1
"""
# ejemplos.py
exec(open('01_introduccion.py').read())

View File

@@ -0,0 +1,80 @@
"""
01_variables.py
"""
# Day 2: 30 Days of Python programming
# Declarando variables
nombre = "Juan"
apellido = "Pérez"
nombre_completo = nombre + " " + apellido
pais = "España"
ciudad = "Madrid"
edad = 30
año = 2021
esta_casado = True
es_verdadero = False
esta_luz_encendida = True
# Declarando múltiples variables en una sola línea
x, y, z = 10, 20, 30
# Imprimiendo tipos de datos
print(type(nombre))
print(type(apellido))
print(type(nombre_completo))
print(type(edad))
print(type(pais))
print(type(esta_casado))
# Encontrando la longitud del nombre
longitud_nombre = len(nombre)
print("La longitud de mi nombre es:", longitud_nombre)
# Comparando la longitud del nombre y el apellido
longitud_apellido = len(apellido)
if longitud_nombre > longitud_apellido:
print("Mi nombre es más largo que mi apellido")
elif longitud_nombre < longitud_apellido:
print("Mi apellido es más largo que mi nombre")
else:
print("Mi nombre y mi apellido tienen la misma longitud")
# Realizando operaciones aritméticas
num_uno = 5
num_dos = 4
total = num_uno + num_dos
diferencia = num_uno - num_dos
producto = num_uno * num_dos
division = num_uno / num_dos
resto = num_dos % num_uno
exp = num_uno ** num_dos
division_piso = num_uno // num_dos
print(total)
print(diferencia)
print(producto)
print(division)
print(resto)
print(exp)
print(division_piso)
# Calculando el área y la circunferencia de un círculo
radio = 30
pi = 3.14159
area_de_circulo = pi * radio ** 2
circunferencia_de_circulo = 2 * pi * radio
print(area_de_circulo)
print(circunferencia_de_circulo)
# Obteniendo información del usuario
nombre = input("Ingresa tu nombre: ")
apellido = input("Ingresa tu apellido: ")
pais = input("Ingresa tu país: ")
edad = input("Ingresa tu edad: ")
# Verificando las palabras clave de Python
help('keywords')

View File

@@ -0,0 +1,45 @@
## Variables, Funciones Incorporadas
Documento original en inglés: [Variables, Builtin Functions](https://github.com/Asabeneh/30-Days-Of-Python/blob/master/02_Day_Variables_builtin_functions/02_variables_builtin_functions.md)
## Ejercicios
### Ejercicios: Nivel 1
- Dentro de `30DaysOfPython`, crea una carpeta llamada `day_2`. Dentro de esta carpeta, crea un archivo llamado `variables.py`.
- Escribe un comentario en Python que diga 'Día 2: Programación de 30 días en Python'.
- Declara una variable `nombre` y asígnale un valor.
- Declara una variable `apellido` y asígnale un valor.
- Declara una variable `nombre_completo` y asígnale un valor.
- Declara una variable `pais` y asígnale un valor.
- Declara una variable `ciudad` y asígnale un valor.
- Declara una variable `edad` y asígnale un valor.
- Declara una variable `año` y asígnale un valor.
- Declara una variable `esta_casado` y asígnale un valor.
- Declara una variable `es_verdadero` y asígnale un valor.
- Declara una variable `esta_luz_encendida` y asígnale un valor.
- Declara múltiples variables en una sola línea.
### Ejercicios: Nivel 2
- Comprueba el tipo de datos de todas tus variables utilizando la función incorporada `type()`.
- Utilizando la función incorporada `len()`, encuentra la longitud de tu nombre.
- Compara la longitud de tu nombre y tu apellido.
- Declara `5` como `num_uno` y `4` como `num_dos`.
- Suma `num_uno` y `num_dos` y asigna el valor a una variable llamada `total`.
- Resta `num_dos` de `num_uno` y asigna el valor a una variable llamada `diferencia`.
- Multiplica `num_uno` y `num_dos` y asigna el valor a una variable llamada `producto`.
- Divide `num_uno` por `num_dos` y asigna el valor a una variable llamada `division`.
- Utiliza la división de módulo para encontrar `num_dos` dividido por `num_uno` y asigna el valor a una variable llamada `resto`.
- Calcula `num_uno` elevado a la potencia de `num_dos` y asigna el valor a una variable llamada `exp`.
- Encuentra la división de piso de `num_uno` por `num_dos` y asigna el valor a una variable llamada `division_piso`.
- El radio de un círculo es de 30 metros.
- Calcula el área de un círculo y asigna el valor a una variable llamada `area_de_circulo`.
- Calcula la circunferencia de un círculo y asigna el valor a una variable llamada `circunferencia_de_circulo`.
- Toma el radio como entrada del usuario y calcula el área.
- Usa la función incorporada `input` para obtener el nombre, apellido, país y edad de un usuario y almacena los valores en las variables correspondientes.
- Ejecuta `help('keywords')` en la terminal de Python o en tu archivo para verificar las palabras reservadas o palabras clave de Python.
[Solución](./variables.py)
[<< Day 1](../01_Introducción/README.md) | [Day 3 >>](../03_Operadores/README.md)

View File

@@ -0,0 +1,126 @@
"""
01_operadores.py
"""
# Ejercicios
# 1. Declara tu edad como una variable entera.
edad = 25
# 2. Declara tu altura como una variable de tipo flotante.
altura = 1.80
# 3. Declara una variable que almacene un número complejo.
num_complejo = 3 + 4j
# 4. Escribe un script que solicite al usuario que ingrese la base y la altura de un triángulo y calcule el área de este triángulo (área = 0.5 x b x h).
base = float(input("Ingresa la base: "))
altura = float(input("Ingresa la altura: "))
area = 0.5 * base * altura
print("El área del triángulo es", area)
# 5. Escribe un script que solicite al usuario que ingrese los lados a, b y c de un triángulo. Calcula el perímetro del triángulo (perímetro = a + b + c).
a = float(input("Ingresa el lado a: "))
b = float(input("Ingresa el lado b: "))
c = float(input("Ingresa el lado c: "))
perimetro = a + b + c
print("El perímetro del triángulo es", perimetro)
# 6. Obtén la longitud y el ancho de un rectángulo utilizando el comando de solicitud (prompt). Calcula su área (área = longitud x ancho) y su perímetro (perímetro = 2 x (longitud + ancho)).
longitud = float(input("Ingresa la longitud: "))
ancho = float(input("Ingresa el ancho: "))
area = longitud * ancho
perimetro = 2 * (longitud + ancho)
print("El área del rectángulo es", area)
print("El perímetro del rectángulo es", perimetro)
# 7. Obten el radio de un círculo utilizando el comando de solicitud (prompt). Calcula el área (área = pi x r x r) y la circunferencia (c = 2 x pi x r), donde pi = 3.14.
radio = float(input("Ingresa el radio del círculo: "))
pi = 3.14
area = pi * radio ** 2
circunferencia = 2 * pi * radio
print("El área del círculo es", area)
print("La circunferencia del círculo es", circunferencia)
# 8. Calcula la pendiente, la intersección en el eje x y la intersección en el eje y de la ecuación y = 2x - 2.
pendiente = 2
interseccion_x = 1
interseccion_y = -2
# 9. La pendiente es (m = y2 - y1 / x2 - x1). Calcula la pendiente y la distancia euclidiana entre el punto (2, 2) y el punto (6, 10).
x1, y1 = 2, 2
x2, y2 = 6, 10
pendiente = (y2 - y1) / (x2 - x1)
distancia = ((x2 - x1) ** 2 + (y2 - y1) ** 2) ** 0.5
print("La pendiente es", pendiente)
print("La distancia euclidiana es", distancia)
# 10. Compara las pendientes en los ejercicios 8 y 9.
# La pendiente en el ejercicio 8 es igual a la pendiente en el ejercicio 9.
# 11. Calcula el valor de y (y = x^2 + 6x + 9). Intenta usar diferentes valores de x y descubre en qué valor de x y será igual a 0.
lista_de_x = [2, -3, 5, -8]
for x in lista_de_x:
y = x ** 2 + 6 * x + 9
print("Si \"x\" es igual a", x, "entonces \"y\" es igual a", y)
# 12. Encuentra la longitud de 'python' y 'dragon' y crea una declaración falsa de comparación.
longitud_python = len("python")
longitud_dragon = len("dragon")
comparacion = longitud_python == longitud_dragon
print("La comparación es", comparacion)
# 13. Utiliza el operador 'and' para verificar si 'on' se encuentra en 'python' y 'dragon'.
en_python = "on" in "python"
en_dragon = "on" in "dragon"
print("Encuentra on en python y dragon: ", en_python and en_dragon)
# 14. Espero que este curso no esté lleno de jerga. Usa el operador 'in' para verificar si 'jerga' está en la oración.
oracion = "Espero que este curso no esté lleno de jerga."
print("Encuentra jerga en la oración:", "jerga" in oracion)
# 15. No hay 'on' ni en dragon ni en python.
# 16. Encuentra la longitud del texto 'python' y convierte el valor a flotante y luego a cadena.
longitud_python = len("python")
longitud_python_flotante = float(longitud_python)
longitud_python_cadena = str(longitud_python_flotante)
print(longitud_python)
print(longitud_python_flotante)
print(longitud_python_cadena)
# 17. Los números pares son divisibles por 2 y el residuo es cero. ¿Cómo puedes verificar si un número es par o no utilizando Python?
numero = 4
es_par = numero % 2 == 0
print("Es par:", es_par)
# 18. Comprueba si la división entera de 7 entre 3 es igual al valor convertido a entero de 2.7.
division_entera = 7 // 3
valor_entero = int(2.7)
comparacion = division_entera == valor_entero
print("Comparación:", comparacion)
# 19. Comprueba si el tipo de '10' es igual al tipo de 10.
tipo_1 = type('10')
tipo_2 = type(10)
comparacion = tipo_1 == tipo_2
print("Comparación:", comparacion)
# 20. Comprueba si int('9.8') es igual a 10.
try:
valor = int('9.8')
except ValueError:
valor = None
comparacion = valor == 10
print("Comparación:", comparacion)
# 21. Escribe un script que solicite al usuario que ingrese las horas y la tarifa por hora. Calcula el salario de la persona.
horas = float(input("Ingresa las horas: "))
tarifa = float(input("Ingresa la tarifa por hora: "))
salario = horas * tarifa
print("Tus ganancias semanales son", salario)
# 22. Escribe un script en Python que muestre la siguiente tabla.
for i in range(1, 6):
print(i, 1, i, i ** 2, i ** 3)

View File

@@ -0,0 +1,7 @@
# Operadores
Documento original en inglés: [Operators](https://github.com/Asabeneh/30-Days-Of-Python/blob/master/03_Day_Operators/03_operators.md)
[Solución](./01_operadores.py)
[<< Day 2](../02_Variables_funciones_incorporadas/README.md) | [Day 4 >>](../04_Cadenas/README.md)

View File

@@ -0,0 +1,153 @@
"""
01_cadenas.py
"""
# 1. Concatenando cadenas
cadena_uno = 'Thirty'
cadena_dos = 'Days'
cadena_tres = 'Of'
cadena_cuatro = 'Python'
cadena_completa = cadena_uno + ' ' + cadena_dos + \
' ' + cadena_tres + ' ' + cadena_cuatro
print(cadena_completa)
# 2. Concatenando cadenas
cadena_uno = 'Coding'
cadena_dos = 'For'
cadena_tres = 'All'
cadena_completa = cadena_uno + ' ' + cadena_dos + ' ' + cadena_tres
print(cadena_completa)
# 3. Declarando una variable
company = 'Coding For All'
# 4. Imprimiendo la variable
print(company)
# 5. Imprimiendo la longitud de la cadena
print(len(company))
# 6. Cambiando a mayúsculas
print(company.upper())
# 7. Cambiando a minúsculas
print(company.lower())
# 8. Formateando la cadena
print(company.capitalize())
print(company.title())
print(company.swapcase())
# 9. Cortando la primera palabra
primera_palabra = company.split()[0]
print(primera_palabra)
# 10. Buscando la palabra 'Coding'
if 'Coding' in company:
print('La cadena contiene la palabra "Coding"')
else:
print('La cadena no contiene la palabra "Coding"')
# 11. Reemplazando la palabra 'coding' por 'Python'
nueva_cadena = company.replace('Coding', 'Python')
print(nueva_cadena)
# 12. Cambiando 'Python for Everyone' a 'Python for All'
nueva_cadena = 'Python for Everyone'.replace('Everyone', 'All')
print(nueva_cadena)
# 13. Dividiendo la cadena
cadena_dividida = company.split()
print(cadena_dividida)
# 14. Dividiendo la cadena por coma
cadena_coma = 'Facebook, Google, Microsoft, Apple, IBM, Oracle, Amazon'
cadena_dividida = cadena_coma.split(',')
print(cadena_dividida)
# 15. Carácter en el índice 0
print(company[0])
# 16. Último índice
print(company[-1])
# 17. Carácter en el índice 10
print(company[10])
# 18. Acrónimo para 'Python For Everyone'
acronimo = ''.join([word[0] for word in 'Python For Everyone'.split()])
print(acronimo)
# 19. Acrónimo para 'Coding For All'
acronimo = ''.join([word[0] for word in 'Coding For All'.split()])
print(acronimo)
# 20. Posición de la primera aparición de 'C'
print(company.index('C'))
# 21. Posición de la primera aparición de 'F'
print(company.index('F'))
# 22. Posición de la última aparición de 'l'
print(company.rfind('l'))
# 23. Posición de la primera aparición de 'because'
frase = 'You cannot end a sentence with because because because is a conjunction'
print(frase.index('because'))
# 24. Posición de la última aparición de 'because'
print(frase.rindex('because'))
# 25. Cortando la frase 'because because because'
frase_cortada = frase[31:47]
print(frase_cortada)
# 26. Posición de la primera aparición de 'because'
print(frase.index('because'))
# 27. Cortando la frase 'because because because'
frase_cortada = frase[31:47]
print(frase_cortada)
# 28. ¿Empieza 'Coding For All' con un subconjunto 'Coding'?
print('Coding For All'.startswith('Coding'))
# 29. ¿Termina 'Coding For All' con un subconjunto 'coding'?
print('Coding For All'.endswith('coding'))
# 30. Eliminando espacios en blanco
cadena = ' Coding For All '
cadena_sin_espacios = cadena.strip()
print(cadena_sin_espacios)
# 31. ¿Cuál de las siguientes variables devuelve True cuando usamos el método `isidentifier()`?
# - 30DaysOfPython
# - thirty_days_of_python
print('30DaysOfPython'.isidentifier())
print('thirty_days_of_python'.isidentifier())
# 32. Uniendo una lista con un hash y espacio
bibliotecas = ['Django', 'Flask', 'Bottle', 'Pyramid', 'Falcon']
cadena_unida = ' # '.join(bibliotecas)
print(cadena_unida)
# 33. Usando la secuencia de escape de nueva línea
print('Estoy disfrutando de este desafío.\nMe pregunto qué sigue.')
# 34. Usando la secuencia de escape de tabulación
print('Nombre\t\tEdad\t\tPaís\t\tCiudad\nAsab\t\t25\t\tPortugal\tLisboa')
# 35. Usando el método de formato de cadena
radio = 10
area = 3.14 * radio ** 2
print(
f"El área de un círculo con radio {radio} es de {area} metros cuadrados.")
# 36. Usando métodos de formato de cadena
print(f"8 + 6 = {8+6}")
print(f"8 - 6 = {8-6}")
print(f"8 * 6 = {8*6}")
print(f"8 / 6 = {8/6:.2f}")
print(f"8 % 6 = {8%6}")
print(f"8 // 6 = {8//6}")
print(f"8 ** 6 = {8**6}")

View File

@@ -0,0 +1,73 @@
# Cadenas
Documento original en inglés: [Strings](https://github.com/Asabeneh/30-Days-Of-Python/blob/master/04_Day_Strings/04_strings.md)
## Ejercicios
1. Concatena las cadenas 'Thirty', 'Days', 'Of' y 'Python' en una sola cadena, 'Thirty Days Of Python'.
2. Concatena las cadenas 'Coding', 'For' y 'All' en una sola cadena, 'Coding For All'.
3. Declara una variable llamada `company` y asígnala al valor inicial "Coding For All".
4. Imprime la variable `company` usando `print()`.
5. Imprime la longitud de la cadena `company` usando el método `len()` y `print()`.
6. Cambia todos los caracteres a letras mayúsculas usando el método `upper()`.
7. Cambia todos los caracteres a letras minúsculas usando el método `lower()`.
8. Usa los métodos `capitalize()`, `title()` y `swapcase()` para formatear el valor de la cadena 'Coding For All'.
9. Corta la primera palabra de la cadena 'Coding For All'.
10. Comprueba si la cadena 'Coding For All' contiene la palabra 'Coding' utilizando los métodos `index`, `find` u otros.
11. Reemplaza la palabra 'coding' en la cadena 'Coding For All' por 'Python'.
12. Cambia 'Python for Everyone' a 'Python for All' utilizando el método `replace` u otros.
13. Divide la cadena 'Coding For All' usando el espacio como separador (split()).
14. Divide la cadena "Facebook, Google, Microsoft, Apple, IBM, Oracle, Amazon" en la coma.
15. ¿Cuál es el carácter en el índice 0 en la cadena 'Coding For All'?
16. ¿Cuál es el último índice de la cadena 'Coding For All'?
17. ¿Qué carácter está en el índice 10 en la cadena "Coding For All"?
18. Crea un acrónimo para el nombre 'Python For Everyone'.
19. Crea un acrónimo para el nombre 'Coding For All'.
20. Usa `index` para determinar la posición de la primera aparición de 'C' en 'Coding For All'.
21. Usa `index` para determinar la posición de la primera aparición de 'F' en 'Coding For All'.
22. Usa `rfind` para determinar la posición de la última aparición de 'l' en 'Coding For All People'.
23. Usa `index` o `find` para encontrar la posición de la primera aparición de la palabra 'because' en la siguiente frase: 'You cannot end a sentence with because because because is a conjunction'.
24. Usa `rindex` para encontrar la posición de la última aparición de la palabra 'because' en la siguiente frase: 'You cannot end a sentence with because because because is a conjunction'.
25. Corta la frase 'because because because' en la siguiente oración: 'You cannot end a sentence with because because because is a conjunction'.
26. Encuentra la posición de la primera aparición de la palabra 'because' en la siguiente oración: 'You cannot end a sentence with because because because is a conjunction'.
27. Corta la frase 'because because because' en la siguiente oración: 'You cannot end a sentence with because because because is a conjunction'.
28. ¿Empieza '\Coding For All' con un subconjunto 'Coding'?
29. ¿Termina 'Coding For All' con un subconjunto 'coding'?
30. '&nbsp;&nbsp; Coding For All &nbsp;&nbsp;&nbsp; &nbsp;', elimina los espacios en blanco a la izquierda y a la derecha en la cadena dada.
31. ¿Cuál de las siguientes variables devuelve True cuando usamos el método `isidentifier()`?
- 30DaysOfPython
- thirty_days_of_python
32. La siguiente lista contiene los nombres de algunas bibliotecas de Python: ['Django', 'Flask', 'Bottle', 'Pyramid', 'Falcon']. Une la lista con una cadena 'hash' con espacio.
33. Usa la secuencia de escape de nueva línea para separar las siguientes oraciones.
```py
Estoy disfrutando de este desafío.
Me pregunto qué sigue.
```
34. Usa la secuencia de escape de tabulación para escribir las siguientes líneas.
```
Nombre Edad País Ciudad
Asabeneh 250 Finlandia Helsinki
```
35. Usa el método de formato de cadena para mostrar lo siguiente:
```
radio = 10
area = 3.14 * radio ** 2
El área de un círculo con radio 10 es de 314 metros cuadrados.
```
36. Haz lo siguiente usando métodos de formato de cadena:
```
8 + 6 = 14
8 - 6 = 2
8 * 6 = 48
8 / 6 = 1.33
8 % 6 = 2
8 // 6 = 1
8 ** 6 = 262144
```
[Solución](./01_cadenas.py)
[<< Day 3](../03_Operadores/README.md) | [Day 5 >>](../05_Listas/README.md)

View File

@@ -0,0 +1,157 @@
"""
01_listas.py
"""
# Ejercicios: Nivel 1
# 1. Declarar una lista vacía.
lista_vacia = []
# 2. Declarar una lista con más de 5 elementos.
lista_mas_cinco = [1, 2, 3, 4, 5, 6, 7]
# 3. Encontrar la longitud de tu lista.
longitud_lista = len(lista_mas_cinco)
# 4. Obtener el primer elemento, el elemento del medio
# y el último elemento de la lista.
primer_elemento = lista_mas_cinco[0]
elemento_medio = lista_mas_cinco[longitud_lista // 2]
ultimo_elemento = lista_mas_cinco[-1]
# 5. Declarar una lista llamada `mixed_data_types`
# e inserta tu (nombre, edad, altura, estado civil, dirección).
mixed_data_types = ['Jorge', 30, 1.75, 'soltero', 'Calle 123']
# 6. Declarar una variable de lista llamada `it_companies`
# y asignar los valores iniciales Facebook, Google, Microsoft,
# Apple, IBM, Oracle y Amazon.
it_companies = ['Facebook', 'Google', 'Microsoft',
'Apple', 'IBM', 'Oracle', 'Amazon']
# 7. Imprime la lista usando `print()`.
print(it_companies)
# 8. Imprime el número de empresas en la lista.
print(len(it_companies))
# 9. Imprime la primera, la del medio y la última empresa.
print(
f"""Primera empresa: {it_companies[0]}
Empresa del medio: {it_companies[len(it_companies) // 2]}
Última empresa: {it_companies[-1]}"""
)
# 10. Imprime la lista después de modificar una de las empresas.
it_companies[0] = 'Mecánica Hernandez'
print(it_companies)
# 11. Agrega una empresa de tecnología a `it_companies`.
it_companies.append('Floristería Rosita')
# 12. Inserta una empresa de tecnología en el medio de la lista de empresas.
it_companies.insert(len(it_companies) // 2, 'Cafetería Don Pepe')
# 13. Cambia uno de los nombres de `it_companies` a mayúsculas (¡excepto IBM!).
it_companies[3] = it_companies[3].upper()
# 14. Une las empresas de tecnología con una cadena '#; '.
empresas_unidas = '#; '.join(it_companies)
# 15. Comprueba si cierta empresa existe en la lista `it_companies`.
comprobar_empresa = 'IBM' in it_companies
print('IBM en la lista:', comprobar_empresa)
# 16. Ordena la lista usando el método `sort()`.
it_companies.sort()
# 17. Invierte la lista en orden descendente usando el método `reverse()`.
it_companies.sort(reverse=True)
# 18. Corta las primeras 3 empresas de la lista.
primeras_tres_empresas = it_companies[:3]
# 19. Corta las últimas 3 empresas de la lista.
ultimas_tres_empresas = it_companies[-3:]
# 20. Corta la empresa o empresas de tecnología del medio de la lista.
empresa_del_medio = it_companies[len(it_companies) // 2]
# 21. Elimina la primera empresa de tecnología de la lista.
it_companies.pop(0)
# 22. Elimina la empresa o empresas de tecnología del medio de la lista.
it_companies.remove(it_companies[len(it_companies) // 2])
# 23. Elimina la última empresa de tecnología de la lista.
it_companies.pop(-1)
# 24. Elimina todas las empresas de tecnología de la lista.
it_companies.clear()
# 25. Destruye la lista de empresas de tecnología.
del it_companies
# 26. Une las siguientes listas:
# front_end = ['HTML', 'CSS', 'JS', 'React', 'Redux']
# back_end = ['Node', 'Express', 'MongoDB']
# Después de unir las listas en la pregunta 26, copia la lista unida
# y asígnala a una variable full_stack.
# Luego, inserta Python y SQL después de Redux.
front_end = ['HTML', 'CSS', 'JS', 'React', 'Redux']
back_end = ['Node', 'Express', 'MongoDB']
joined_list = front_end + back_end
full_stack = joined_list.copy()
full_stack.insert(full_stack.index('Redux') + 1, 'Python')
full_stack.insert(full_stack.index('Redux') + 2, 'SQL')
print(full_stack)
# Ejercicios: Nivel 2
# 1. La siguiente es una lista de edades de 10 estudiantes:
# edades = [19, 22, 19, 24, 20, 25, 26, 24, 25, 24]
edades = [19, 22, 19, 24, 20, 25, 26, 24, 25, 24]
# - Ordena la lista y encuentra la edad mínima y máxima.
edades.sort()
edad_min = edades[0]
edad_max = edades[-1]
# - Agrega nuevamente la edad mínima y máxima a la lista.
edades.append(edad_min)
edades.append(edad_max)
# - Encuentra la edad mediana (un solo elemento medio
# o dos elementos medios divididos por dos).
edad_mediana = edades[len(edades) // 2]
print(edad_mediana)
# - Encuentra la edad promedio (suma de todos los elementos divididos por su número).
edad_promedio = sum(edades) / len(edades)
print(edad_promedio)
# - Encuentra el rango de las edades (máximo menos mínimo).
rangos_edades = edad_max - edad_min
# - Compara el valor de (mínimo - promedio) y (máximo - promedio), usa el método abs().
abs_min_promedio = abs(edad_min - edad_promedio)
abs_max_promedio = abs(edad_max - edad_promedio)
# 2. Encuentra el país o países del medio en la lista de países.
# ['China', 'Rusia', 'EE. UU.', 'Finlandia', 'Suecia', 'Noruega', 'Dinamarca']
# - Divide la lista de países en dos listas iguales si es par;
# si no, agrega un país más para la primera mitad.
paises = ['China', 'Rusia', 'EE. UU.',
'Finlandia', 'Suecia', 'Noruega', 'Dinamarca']
if len(paises) % 2 == 0:
primera_mitad = paises[:len(paises) // 2]
segunda_mitad = paises[len(paises) // 2:]
else:
primera_mitad = paises[:len(paises) // 2 + 1]
segunda_mitad = paises[len(paises) // 2 + 1:]
print(primera_mitad, ',', segunda_mitad)
# - Desempaqueta los primeros tres países y el resto como países escandinavos.
primer_pais, segundo_pais, tercer_pais, *paises_escandinavos = paises
print(primer_pais, segundo_pais, tercer_pais, paises_escandinavos)

View File

@@ -0,0 +1,91 @@
# Listas
Documento original en inglés: [List](https://github.com/Asabeneh/30-Days-Of-Python/blob/master/05_Day_Lists/05_lists.md)
## Ejercicios
### Ejercicios: Nivel 1
1. Declarar una lista vacía.
2. Declarar una lista con más de 5 elementos.
3. Encontrar la longitud de tu lista.
4. Obtener el primer elemento, el elemento del medio y el último elemento de la lista.
5. Declarar una lista llamada `mixed_data_types` e inserta tu (nombre, edad, altura, estado civil, dirección).
6. Declarar una variable de lista llamada `it_companies` y asignar los valores iniciales Facebook, Google, Microsoft, Apple, IBM, Oracle y Amazon.
7. Imprime la lista usando `print()`.
8. Imprime el número de empresas en la lista.
9. Imprime la primera, la del medio y la última empresa.
10. Imprime la lista después de modificar una de las empresas.
11. Agrega una empresa de tecnología a `it_companies`.
12. Inserta una empresa de tecnología en el medio de la lista de empresas.
13. Cambia uno de los nombres de `it_companies` a mayúsculas (¡excepto IBM!).
14. Une las empresas de tecnología con una cadena '#; '.
15. Comprueba si cierta empresa existe en la lista `it_companies`.
16. Ordena la lista usando el método `sort()`.
17. Invierte la lista en orden descendente usando el método `reverse()`.
18. Corta las primeras 3 empresas de la lista.
19. Corta las últimas 3 empresas de la lista.
20. Corta la empresa o empresas de tecnología del medio de la lista.
21. Elimina la primera empresa de tecnología de la lista.
22. Elimina la empresa o empresas de tecnología del medio de la lista.
23. Elimina la última empresa de tecnología de la lista.
24. Elimina todas las empresas de tecnología de la lista.
25. Destruye la lista de empresas de tecnología.
26. Une las siguientes listas:
```
front_end = ['HTML', 'CSS', 'JS', 'React', 'Redux']
back_end = ['Node', 'Express', 'MongoDB']
```
Después de unir las listas en la pregunta 26, copia la lista unida y asígnala a una variable full_stack. Luego, inserta Python y SQL después de Redux.
### Ejercicios: Nivel 2
1. La siguiente es una lista de edades de 10 estudiantes:
```
edades = [19, 22, 19, 24, 20, 25, 26, 24, 25, 24]
```
- Ordena la lista y encuentra la edad mínima y máxima.
- Agrega nuevamente la edad mínima y máxima a la lista.
- Encuentra la edad mediana (un solo elemento medio o dos elementos medios divididos por dos).
- Encuentra la edad promedio (suma de todos los elementos divididos por su número).
- Encuentra el rango de las edades (máximo menos mínimo).
- Compara el valor de (mínimo - promedio) y (máximo - promedio), usa el método abs().
2. Encuentra el país o países del medio en la lista de países.
- Divide la lista de países en dos listas iguales si es par; si no, agrega un país más para la primera mitad.
```
['China', 'Rusia', 'EE. UU.', 'Finlandia', 'Suecia', 'Noruega', 'Dinamarca']
```
- Desempaqueta los primeros tres países y el resto como países escandinavos.
[Solución](./01_listas.py)
[<< Day 4](../04_Cadenas/README.md) | [Day 6 >>](../06_Tuplas/README.md)

View File

@@ -0,0 +1,60 @@
"""
01_tuplas.py
"""
# 1. Crea una tupla vacía.
empty_tuple = ()
# 2. Crea una tupla que contenga los nombres de tus hermanas y hermanos (hermanos imaginarios están bien).
hermanos_tuple = ('Mario', 'Maria', 'Juan', 'Juana')
# 3. Une las tuplas de hermanos y hermanas y asígnalo a `siblings`.
siblings = hermanos_tuple
# 4. ¿Cuántos hermanos tienes?
numero_hermanos = len(siblings)
print(f'Tienes {numero_hermanos} hermanos')
# 5. Modifica la tupla `siblings` y agrega el nombre de tu padre y madre, asígnalo a `family_members`.
family_members = siblings + ('padre', 'madre')
# 6. Desempaqueta hermanos y padres de `family_members`.
hermano1, hermana1, hermano2, hermana2, padre, madre = family_members
# 7. Crea tuplas de frutas, verduras y productos de origen animal. Une las tres tuplas y asígnalo a una variable llamada `food_stuff_tp`.
frutas = ('manzana', 'banana', 'naranja')
verduras = ('lechuga', 'tomate', 'cebolla')
productos_animal = ('miel', 'huevos', 'caviar')
food_stuff_tp = frutas + verduras + productos_animal
# 8. Cambia la tupla `food_stuff_tp` a una lista llamada `food_stuff_lt`.
food_stuff_lt = list(food_stuff_tp)
# 9. Corta el elemento o elementos del medio de la tupla `food_stuff_tp` o la lista `food_stuff_lt`.
if len(food_stuff_lt) % 2 == 0:
food_stuff_lt = food_stuff_lt[:len(
food_stuff_lt) // 2 - 1] + food_stuff_lt[len(food_stuff_lt) // 2 + 1:]
else:
food_stuff_lt = food_stuff_lt[:len(
food_stuff_lt) // 2] + food_stuff_lt[len(food_stuff_lt) // 2 + 1:]
# 10. Corta los tres primeros elementos y los tres últimos elementos de la lista `food_stuff_lt`.
food_stuff_lt = food_stuff_lt[3:-3]
# 11. Elimina completamente la tupla `food_staff_tp`.
del food_stuff_tp
# 12. Verifica si un elemento existe en la tupla:
nordic_countries = ('Dinamarca', 'Finlandia', 'Islandia', 'Noruega', 'Suecia')
# - Verifica si 'Estonia' es un país nórdico.
if 'Estonia' in nordic_countries:
print('Estonia es un país nórdico')
else:
print('Estonia no es un país nórdico')
# - Verifica si 'Iceland' es un país nórdico.
if 'Iceland' in nordic_countries:
print('Iceland es un país nórdico')
else:
print('Iceland no es un país nórdico')

View File

@@ -0,0 +1,44 @@
# Tuplas
Documento original en inglés: [tuples](https://github.com/Asabeneh/30-Days-Of-Python/blob/master/06_Day_Tuples/06_tuples.md)
## Ejercicios
### Ejercicios: Nivel 1
1. Crea una tupla vacía.
2. Crea una tupla que contenga los nombres de tus hermanas y hermanos (hermanos imaginarios están bien).
3. Une las tuplas de hermanos y hermanas y asígnalo a `siblings`.
4. ¿Cuántos hermanos tienes?
5. Modifica la tupla `siblings` y agrega el nombre de tu padre y madre, asígnalo a `family_members`.
**Ejercicios: Nivel 2**
6. Desempaqueta hermanos y padres de `family_members`.
7. Crea tuplas de frutas, verduras y productos de origen animal. Une las tres tuplas y asígnalo a una variable llamada `food_stuff_tp`.
8. Cambia la tupla `food_stuff_tp` a una lista llamada `food_stuff_lt`.
9. Corta el elemento o elementos del medio de la tupla `food_stuff_tp` o la lista `food_stuff_lt`.
10. Corta los tres primeros elementos y los tres últimos elementos de la lista `food_stuff_lt`.
11. Elimina completamente la tupla `food_staff_tp`.
12. Verifica si un elemento existe en la tupla:
- Verifica si 'Estonia' es un país nórdico.
- Verifica si 'Iceland' es un país nórdico.
```
nordic_countries = ('Dinamarca', 'Finlandia', 'Islandia', 'Noruega', 'Suecia')
```
[Solución](01_tuplas.py)
[<< Day 5](../05_Listas/README.md) | [Day 7 >>](../07_Conjuntos/README.md)

View File

@@ -0,0 +1,78 @@
"""
01_conjuntos.py
"""
# Ejercicios: Nivel 1
# Conjuntos
it_companies = {'Facebook', 'Google', 'Microsoft',
'Apple', 'IBM', 'Oracle', 'Amazon'}
A = {19, 22, 24, 20, 25, 26}
B = {19, 22, 20, 25, 26, 24, 28, 27}
age = [22, 19, 24, 25, 26, 24, 25, 24]
# 1. Encuentra la longitud del conjunto `it_companies`.
it_companies_length = len(it_companies)
print(f'La longitud de it_companies es {it_companies_length}')
# 2. Agrega 'Twitter' a `it_companies`.
it_companies.add('Twitter')
# 3. Inserta varias compañías de TI a la vez en el conjunto `it_companies`.
it_companies.update(['Intel', 'HP', 'Dell'])
# 4. Elimina una de las compañías del conjunto `it_companies`.
it_companies.remove('Dell')
# 5. ¿Cuál es la diferencia entre `remove` y `discard`?
# La diferencia es que si el elemento no existe en el conjunto,
# `remove` levanta una excepción, mientras que `discard` no hace nada.
# Ejercicios: Nivel 2
# 1. Une los conjuntos A y B.
A_union_B = A.union(B)
# 2. Encuentra la intersección entre A y B.
A_intersection_B = A.intersection(B)
# 3. ¿Es A un subconjunto de B?
A_is_subset_of_B = A.issubset(B)
# 4. ¿Son A y B conjuntos disjuntos?
A_and_B_are_disjoint = A.isdisjoint(B)
# 5. Une A con B y B con A.
A.update(B)
B.update(A)
# 6. ¿Cuál es la diferencia simétrica entre A y B?
A_symmetric_difference_B = A.symmetric_difference(B)
# 7. Elimina completamente los conjuntos.
del it_companies
del A
del B
# Ejercicios: Nivel 3
# 1. Convierte las edades a un conjunto y compara la longitud de la lista y el conjunto, ¿cuál es más grande?
age_set = set(age)
if len(age_set) > len(age):
print('El conjunto de edades es más grande que la lista de edades')
elif len(age_set) < len(age):
print('La lista de edades es más grande que el conjunto de edades')
else:
print('La lista de edades y el conjunto de edades tienen la misma longitud')
# 2. Explica la diferencia entre los siguientes tipos de datos: cadena (string), lista (list), tupla (tuple) y conjunto (set).
# Una cadena (string) es una secuencia de caracteres.
# Una lista (list) es una colección ordenada y mutable de elementos.
# Una tupla (tuple) es una colección ordenada e inmutable de elementos.
# Un conjunto (set) es una colección no ordenada y mutable de elementos únicos.
# 3. Soy un profesor y me encanta inspirar y enseñar a la gente.
# ¿Cuántas palabras únicas se han utilizado en la oración?
# Utiliza los métodos `split` y `set` para obtener las palabras únicas.
sentence = 'Soy un profesor y me encanta inspirar y enseñar a la gente'
unique_words = set(sentence.split())
number_of_unique_words = len(unique_words)
print(f'Hay {number_of_unique_words} palabras únicas en la oración')

View File

@@ -0,0 +1,52 @@
# Conjuntos
Documento original en inglés: [Sets](https://github.com/Asabeneh/30-Days-Of-Python/blob/master/07_Day_Sets/07_sets.md)
## Ejercicios
```
# Conjuntos
it_companies = {'Facebook', 'Google', 'Microsoft', 'Apple', 'IBM', 'Oracle', 'Amazon'}
A = {19, 22, 24, 20, 25, 26}
B = {19, 22, 20, 25, 26, 24, 28, 27}
age = [22, 19, 24, 25, 26, 24, 25, 24]
```
### Ejercicios: Nivel 1
1. Encuentra la longitud del conjunto `it_companies`.
2. Agrega 'Twitter' a `it_companies`.
3. Inserta varias compañías de TI a la vez en el conjunto `it_companies`.
4. Elimina una de las compañías del conjunto `it_companies`.
5. ¿Cuál es la diferencia entre `remove` y `discard`?
### Ejercicios: Nivel 2
1. Une los conjuntos A y B.
2. Encuentra la intersección entre A y B.
3. ¿Es A un subconjunto de B?
4. ¿Son A y B conjuntos disjuntos?
5. Une A con B y B con A.
6. ¿Cuál es la diferencia simétrica entre A y B?
7. Elimina completamente los conjuntos.
### Ejercicios: Nivel 3
1. Convierte las edades a un conjunto y compara la longitud de la lista y el conjunto, ¿cuál es más grande?
2. Explica la diferencia entre los siguientes tipos de datos: cadena (string), lista (list), tupla (tuple) y conjunto (set).
3. Soy un profesor y me encanta inspirar y enseñar a la gente. ¿Cuántas palabras únicas se han utilizado en la oración? Utiliza los métodos `split` y `set` para obtener las palabras únicas.
[Solución](./01_sets.py)
[<< Day 6](../06_Tuplas/README.md) | [Day 8 >>](../08_Diccionarios/README.md)

View File

@@ -0,0 +1,55 @@
"""
01_dic.py
"""
# 1. Crea un diccionario vacío llamado `perro`.
perro = {}
# 2. Agrega las claves `nombre`, `color`, `raza`, `patas` y `edad` al diccionario `perro`.
perro['nombre'] = 'Rintintin'
perro['color'] = 'blanco y negro'
perro['raza'] = 'Mestizo'
perro['patas'] = 4
perro['edad'] = 2
# 3. Crea un diccionario llamado `estudiante` y agrega las siguientes claves: `nombre`, `apellido`, `género`, `edad`, `estado civil`, `habilidades`, `país`, `ciudad` y `dirección`.
estudiante = {
'nombre': 'Armando',
'apellido': 'Guerra',
'género': 'Indefinido',
'edad': 28,
'estado civil': 'Soltero',
'habilidades': ['Python', 'JavaScript'],
'país': 'México',
'ciudad': 'Ciudad de México',
'dirección': 'Calle Libertadores, 23 7º 2ª'
}
# 4. Obtiene la longitud del diccionario `estudiante`.
estudiante_length = len(estudiante)
print(f"El diccionario estudiante tiene {estudiante_length} valores")
# 5. Obtiene el valor de `habilidades` y verifica su tipo de dato, que debería ser una lista.
habilidades = estudiante['habilidades']
if type(habilidades) == list:
print(f'El valor de habilidades es una lista: {type(habilidades)}')
# 6. Modifica los valores de `habilidades` agregando una o dos habilidades más.
estudiante['habilidades'].extend(['HTML', 'CSS'])
# 7. Obtiene las claves del diccionario como una lista.
estudiante_keys = list(estudiante.keys())
print(f'Las claves del diccionario estudiante son: {estudiante_keys}')
# 8. Obtiene los valores del diccionario como una lista.
estudiante_values = list(estudiante.values())
print(f'Los valores del diccionario estudiante son: {estudiante_values}')
# 9. Convierte el diccionario en una lista de tuplas utilizando el método `items()`.
estudiante_items = list(estudiante.items())
# 10. Elimina uno de los elementos del diccionario.
del estudiante['habilidades']
# 11. Elimina uno de los diccionarios por completo.
del perro

View File

@@ -0,0 +1,31 @@
# Diccionarios
Documento original en inglés: [Dictionaries](https://github.com/Asabeneh/30-Days-Of-Python/blob/master/08_Day_Dictionaries/08_dictionaries.md)
## Ejercicios
1. Crea un diccionario vacío llamado `perro`.
2. Agrega las claves `nombre`, `color`, `raza`, `patas` y `edad` al diccionario `perro`.
3. Crea un diccionario llamado `estudiante` y agrega las siguientes claves: `nombre`, `apellido`, `género`, `edad`, `estado civil`, `habilidades`, `país`, `ciudad` y `dirección`.
4. Obtiene la longitud del diccionario `estudiante`.
5. Obtiene el valor de `habilidades` y verifica su tipo de dato, que debería ser una lista.
6. Modifica los valores de `habilidades` agregando una o dos habilidades más.
7. Obtiene las claves del diccionario como una lista.
8. Obtiene los valores del diccionario como una lista.
9. Convierte el diccionario en una lista de tuplas utilizando el método `items()`.
10. Elimina uno de los elementos del diccionario.
11. Elimina uno de los diccionarios por completo.
[Solución](01_dic.py)
[<< Day 7](../07_Conjuntos/README.md) | [Day 9 >>](../09_Condicionales/README.md)

View File

@@ -0,0 +1,164 @@
"""
01_condicionales.py
"""
# Ejercicios: Nivel 1
# 1. Obtiene la entrada del usuario utilizando `input("Ingresa tu edad: ")`.
# Si el usuario tiene 18 años o más, muestra el mensaje: "Eres lo suficientemente mayor para conducir".
# Si es menor de 18 años, muestra el mensaje que indique cuántos años faltan para poder aprender a conducir.
edad = int(input("Ingresa tu edad: "))
if edad > 65:
print("Quizá en la jubilación no es el mejor momento para aprender a conducir.")
elif edad < 18:
print(f"Necesitas {18 - edad} años más para aprender a conducir.")
else:
print("Eres lo suficientemente mayor para aprender a conducir.")
# 2. Compara los valores de `mi_edad` y `tu_edad` usando `if... else`.
# ¿Quién es mayor (yo o tú)?
# Utiliza `input("Ingresa tu edad: ")` para obtener la edad como entrada.
# Puedes utilizar una condición anidada para imprimir "año" para una diferencia de edad de 1 año,
# "años" para diferencias mayores y un texto personalizado si `mi_edad` es igual a `tu_edad`.
mi_edad = 32
tu_edad = int(input("Ingresa tu edad: "))
diferencia = mi_edad - tu_edad
if mi_edad > tu_edad:
if diferencia == 1:
print(f"Yo soy {diferencia} año mayor que tú.")
else:
print(f"Yo soy {diferencia} años mayor que tú.")
elif mi_edad < tu_edad:
if diferencia == 1:
print(f"Tú eres {diferencia} año mayor que yo.")
else:
print(f"Tú eres {diferencia} años mayor que yo.")
else:
print("Tenemos la misma edad.")
# 3. Obtiene dos números del usuario utilizando el prompt `input`.
# Si `a` es mayor que `b`, devuelve "a es mayor que b".
# Si `a` es menor que `b`, devuelve "a es menor que b".
# En caso contrario, devuelve "a es igual a b".
a = int(input("Ingresa el número a: "))
b = int(input("Ingresa el número b: "))
if a > b:
print(f"El número a ({a}) es mayor que el número b ({b})")
elif a < b:
print(f"El número a ({a}) es menor que el número b ({b})")
else:
print(f"El número a ({a}) es igual al número b ({b})")
# Ejercicios: Nivel 2
# 1. Escribe un código que asigne una calificación
# a los estudiantes según sus puntuaciones:
# 80-100: A
# 70-89: B
# 60-69: C
# 50-59: D
# 0-49: F
puntuacion = int(
input("Ingresa la puntuación del estudiante (Entre 0 y 100): "))
if puntuacion >= 80:
print("A")
elif puntuacion >= 70:
print("B")
elif puntuacion >= 60:
print("C")
elif puntuacion >= 50:
print("D")
else:
print("F")
# 2. Comprueba si la estación es Otoño, Invierno, Primavera o Verano.
# Si la entrada del usuario es: Septiembre, Octubre o Noviembre, la estación es Otoño.
# Si la entrada es: Diciembre, Enero o Febrero, la estación es Invierno.
# Si la entrada es: Marzo, Abril o Mayo, la estación es Primavera.
# Si la entrada es: Junio, Julio o Agosto, la estación es Verano.
mes = input("Ingresa el mes: ")
if mes in ['Diciembre', 'Enero', 'Febrero']:
print("Invierno")
elif mes in ['Marzo', 'Abril', 'Mayo']:
print("Primavera")
elif mes in ['Junio', 'Julio', 'Agosto']:
print("Verano")
else:
print("Otoño")
# 3. La siguiente lista contiene algunas frutas:
# frutas = ['banana', 'naranja', 'mango', 'limón']
# Si una fruta no existe en la lista, agrégala y muestra la lista modificada.
# Si la fruta ya existe, muestra el mensaje "Esa fruta ya existe en la lista".
frutas = ['banana', 'naranja', 'mango', 'limón']
fruta = input("Ingresa una fruta: ")
if fruta in frutas:
print("Esa fruta ya existe en la lista.")
else:
frutas.append(fruta)
print('\n'.join(frutas))
# Ejercicios: Nivel 3
# Aquí tenemos un diccionario llamado `persona`.
# ¡Siéntete libre de modificarlo!
persona = {
'nombre': 'Armando',
'apellido': 'Guerra',
'edad': 32,
'país': 'Guatemala',
'casado': True,
'habilidades': ['JavaScript', 'React', 'Node', 'MongoDB', 'Python'],
'dirección': {
'calle': 'Calle Espacial',
'código postal': '02210'
}
}
# Comprueba si el diccionario persona tiene una clave llamada habilidades,
# si es así, imprime la habilidad intermedia de la lista de habilidades.
if 'habilidades' in persona:
habilidades = persona['habilidades']
habilidades_length = len(habilidades)
if habilidades_length % 2 == 0:
index = habilidades_length // 2 - 1
habilidad_intermedia = habilidades[index:index+2]
else:
index = habilidades_length // 2
habilidad_intermedia = habilidades[index]
print(f"Habilidad intermedia: {habilidad_intermedia}")
# Comprueba si el diccionario persona tiene una clave llamada habilidades,
# si es así, verifica si la persona tiene la habilidad 'Python' e imprime el resultado.
if 'habilidades' in persona:
habilidades = persona['habilidades']
if 'Python' in habilidades:
print("La persona tiene la habilidad 'Python'.")
else:
print("La persona no tiene la habilidad 'Python'.")
# Si las habilidades de una persona son solo JavaScript y React,
# imprime "Es un desarrollador front-end".
# Si las habilidades incluyen Node, Python y MongoDB,
# imprime "Es un desarrollador back-end".
# Si las habilidades incluyen React, Node y MongoDB,
# imprime "Es un desarrollador fullstack".
# En caso contrario, imprime "título desconocido".
if 'habilidades' in persona:
habilidades = persona['habilidades']
if habilidades == ['JavaScript', 'React']:
print("Es un desarrollador front-end.")
elif set(habilidades) == set(['Node', 'Python', 'MongoDB']):
print("Es un desarrollador back-end.")
elif set(habilidades) == set(['React', 'Node', 'MongoDB']):
print("Es un desarrollador fullstack.")
else:
print("Título desconocido.")
# Si la persona está casada y vive en Guatemala,
# imprime la información en el siguiente formato:
# Asabeneh Yetayeh vive en Guatemala. Está casado.
if 'casado' in persona and 'país' in persona:
if persona['casado'] and persona['país'] == 'Guatemala':
nombre_completo = persona['nombre'] + ' ' + persona['apellido']
print(f"{nombre_completo} vive en Guatemala. Está casado.")

View File

@@ -0,0 +1,87 @@
# Condicionales
Documento original en inglés: [Conditionals](https://github.com/Asabeneh/30-Days-Of-Python/blob/master/09_Day_Conditionals/09_conditionals.md)
## Ejercicios
# Ejercicios: Nivel 1
1. Obtiene la entrada del usuario utilizando `input("Ingresa tu edad: ")`. Si el usuario tiene 18 años o más, muestra el mensaje: "Eres lo suficientemente mayor para conducir". Si es menor de 18 años, muestra el mensaje que indique cuántos años faltan para poder aprender a conducir. **Output:**
```
Ingresa tu edad: 30
Eres lo suficientemente mayor para aprender a conducir.
```
**Output:**
```
Ingresa tu edad: 15
Necesitas 3 años más para aprender a conducir.
```
2. Compara los valores de `mi_edad` y `tu_edad` usando `if... else`. ¿Quién es mayor (yo o tú)? Utiliza `input("Ingresa tu edad: ")` para obtener la edad como entrada. Puedes utilizar una condición anidada para imprimir "año" para una diferencia de edad de 1 año, "años" para diferencias mayores y un texto personalizado si `mi_edad` es igual a `tu_edad`. **Output:**
```
Ingresa tu edad: 30
Tu eres 5 años mayor que yo.
```
3. Obtiene dos números del usuario utilizando el prompt `input`. Si `a` es mayor que `b`, devuelve "a es mayor que b". Si `a` es menor que `b`, devuelve "a es menor que b". En caso contrario, devuelve "a es igual a b". **Output:**
```
Ingresa el número uno: 4
Ingresa el número dos: 3
4 es mayor que 3
```
## Ejercicios: Nivel 2
1. Escribe un código que asigne una calificación a los estudiantes según sus puntuaciones:
```
80-100: A
70-89: B
60-69: C
50-59: D
0-49: F
```
2. Comprueba si la estación es Otoño, Invierno, Primavera o Verano. Si la entrada del usuario es: Septiembre, Octubre o Noviembre, la estación es Otoño. Si la entrada es: Diciembre, Enero o Febrero, la estación es Invierno. Si la entrada es: Marzo, Abril o Mayo, la estación es Primavera. Si la entrada es: Junio, Julio o Agosto, la estación es Verano.
3. La siguiente lista contiene algunas frutas:
```
frutas = ['banana', 'naranja', 'mango', 'limón']
```
Si una fruta no existe en la lista, agrégala a la lista y muestra la lista modificada. Si la fruta ya existe, muestra el mensaje "Esa fruta ya existe en la lista".
## Ejercicios: Nivel 3
Aquí tenemos un diccionario llamado `persona`. ¡Siéntete libre de modificarlo!
```python
persona = {
'nombre': 'Asabeneh',
'apellido': 'Yetayeh',
'edad': 250,
'país': 'Finlandia',
'casado': True,
'habilidades': ['JavaScript', 'React', 'Node', 'MongoDB', 'Python'],
'dirección': {
'calle': 'Calle Espacial',
'código postal': '02210'
}
}
```
- Comprueba si el diccionario persona tiene una clave llamada habilidades y, si es así, imprime la habilidad intermedia de la lista de habilidades.
- Comprueba si el diccionario persona tiene una clave llamada habilidades y, si es así, verifica si la persona tiene la habilidad 'Python' e imprime el resultado.
- Si las habilidades de una persona son solo JavaScript y React, imprime "Es un desarrollador front-end". Si las habilidades incluyen Node, Python y MongoDB, imprime "Es un desarrollador back-end". Si las habilidades incluyen React, Node y MongoDB, imprime "Es un desarrollador fullstack". En caso contrario, imprime "título desconocido".
- Si la persona está casada y vive en Finlandia, imprime la información en el siguiente formato:
-
```
Asabeneh Yetayeh vive en Finlandia. Está casado.
```
[Solución](./01_condicionales.py)
[<< Day 8](../08_Diccionarios/README.md) | [Day 10 >>](../10_Bucles/README.md)

View File

@@ -0,0 +1,55 @@
"""
01_bucles.py
"""
# Ejercicios: Nivel 1
# 1. Itera de 0 a 10 utilizando un bucle for,
# haz lo mismo utilizando un bucle while.
for i in range(11):
print(i)
i = 0
while i <= 10:
print(i)
i += 1
# 2. Itera de 10 a 0 utilizando un bucle for,
# haz lo mismo utilizando un bucle while.
for i in range(10, -1, -1):
print(i)
i = 10
while i >= 0:
print(i)
i -= 1
# 3. Escribe un bucle que haga siete llamadas a `print()`,
# de modo que obtengamos el siguiente triángulo en la salida:
for i in range(1, 8):
print('#' * i)
# 4. Utiliza bucles anidados para crear lo siguiente:
for i in range(8):
for j in range(8):
print('#', end=' ')
print()
# 5. Imprime el siguiente patrón:
for i in range(11):
print(f'{i} x {i} = {i*i}')
# 6. Itera a través de la lista
# `['Python', 'Numpy', 'Pandas', 'Django', 'Flask']`
# utilizando un bucle for e imprime los elementos.
for elemento in ['Python', 'Numpy', 'Pandas', 'Django', 'Flask']:
print(elemento)
# 7. Utiliza un bucle for para iterar de 0 a 100
# e imprime solo los números pares.
for i in range(0, 101, 2):
print(i)
# 8. Utiliza un bucle for para iterar de 0 a 100
# e imprime solo los números impares.
for i in range(1, 101, 2):
print(i)

View File

@@ -0,0 +1,25 @@
"""
02_bucles.py
"""
# Ejercicios: Nivel 2
# 1. Utiliza un bucle for para iterar de 0 a 100
# e imprime la suma de todos los números.
suma_total = 0
for i in range(101):
suma_total += i
print(f'La suma de todos los números es {suma_total}.')
# 2. Utiliza un bucle for para iterar de 0 a 100
# e imprime la suma de todos los números pares
# y la suma de todos los números impares.
suma_pares = 0
suma_impares = 0
for i in range(101):
if i % 2 == 0:
suma_pares += i
else:
suma_impares += i
print(
f'La suma de todos los números pares es {suma_pares}. \nLa suma de todos los números impares es {suma_impares}.')

View File

@@ -0,0 +1,60 @@
"""
03_bucles.py
"""
# Ejercicios: Nivel 3
import os
import sys
import json
import countries
# 1. Ve a la carpeta de datos y utiliza el archivo countries.py.
# Recorre los países y extrae todos los países
# que contienen la palabra "land".
sys.path.append(os.path.join(os.getcwd(), 'data'))
for country in countries.countries:
if 'land' in country:
print(country)
# 2. Esta es una lista de frutas: `['banana', 'naranja', 'mango', 'limón']`.
# Invierte el orden utilizando un bucle.
frutas = ['banana', 'naranja', 'mango', 'limón']
for i in range(len(frutas) - 1, -1, -1):
print(frutas[i])
# 3. Ve a la carpeta de datos y utiliza el archivo countries_data.py.
with open(os.path.join('data', 'countries_data.json')) as f:
countries_data = json.load(f)
# ¿Cuál es el número total de idiomas en los datos?
idiomas = set()
for country in countries_data:
for language in country['languages']:
idiomas.add(language)
print(f'El número total de idiomas en los datos es {len(idiomas)}.')
# Encuentra los diez idiomas más hablados en los datos.
idiomas_hablados = {}
for country in countries_data:
for language in country['languages']:
if language in idiomas_hablados:
idiomas_hablados[language] += country['population']
else:
idiomas_hablados[language] = country['population']
idiomas_top_10 = sorted(idiomas_hablados.items(),
key=lambda x: x[1], reverse=True)[:10]
print('Los diez idiomas más hablados en los datos son:')
for idioma, poblacion in idiomas_top_10:
print(f'{idioma}: {poblacion}')
# Encuentra los 10 países más poblados del mundo.
paises_top_10 = sorted(
countries_data, key=lambda x: x['population'], reverse=True)[:10]
print('Los diez países más poblados del mundo son:')
for pais in paises_top_10:
print(f"{pais['name']}: {pais['population']} habitantes.")

View File

@@ -0,0 +1,89 @@
# Bucles
Documento original en inglés: [Loops](https://github.com/Asabeneh/30-Days-Of-Python/blob/master/10_Day_Loops/10_loops.md)
## Ejercicios
# Ejercicios: Nivel 1
1. Itera de 0 a 10 utilizando un bucle for, haz lo mismo utilizando un bucle while.
2. Itera de 10 a 0 utilizando un bucle for, haz lo mismo utilizando un bucle while.
3. Escribe un bucle que haga siete llamadas a `print()`, de modo que obtengamos el siguiente triángulo en la salida:
```
#
##
###
####
#####
######
#######
```
4. Utiliza bucles anidados para crear lo siguiente:
```
# # # # # # # #
# # # # # # # #
# # # # # # # #
# # # # # # # #
# # # # # # # #
# # # # # # # #
# # # # # # # #
# # # # # # # #
```
5. Imprime el siguiente patrón:
```
0 x 0 = 0
1 x 1 = 1
2 x 2 = 4
3 x 3 = 9
4 x 4 = 16
5 x 5 = 25
6 x 6 = 36
7 x 7 = 49
8 x 8 = 64
9 x 9 = 81
10 x 10 = 100
```
6. Itera a través de la lista `['Python', 'Numpy', 'Pandas', 'Django', 'Flask']` utilizando un bucle for e imprime los elementos.
7. Utiliza un bucle for para iterar de 0 a 100 e imprime solo los números pares.
8. Utiliza un bucle for para iterar de 0 a 100 e imprime solo los números impares.
[Solución](01_bucles.py)
## Ejercicios: Nivel 2
1. Utiliza un bucle for para iterar de 0 a 100 e imprime la suma de todos los números.
```
La suma de todos los números es 5050.
```
2. Utiliza un bucle for para iterar de 0 a 100 e imprime la suma de todos los números pares y la suma de todos los números impares.
```
La suma de todos los números pares es 2550. Y la suma de todos los números impares es 2500.
```
[Solución](02_bucles.py)
## Ejercicios: Nivel 3
1. Ve a la carpeta de datos y utiliza el archivo countries.py. Recorre los países y extrae todos los países que contienen la palabra "land".
2. Esta es una lista de frutas: `['banana', 'naranja', 'mango', 'limón']`. Invierte el orden utilizando un bucle.
3. Ve a la carpeta de datos y utiliza el archivo countries_data.py.
- ¿Cuál es el número total de idiomas en los datos?
- Encuentra los diez idiomas más hablados en los datos.
- Encuentra los 10 países más poblados del mundo.
[Solución](03_bucles.py)
[<< Day 9](../09_Condicionales/README.md) | [Day 11 >>](../11_Funciones/README.md)

View File

@@ -0,0 +1,195 @@
countries = [
'Afghanistan',
'Albania',
'Algeria',
'Andorra',
'Angola',
'Antigua and Barbuda',
'Argentina',
'Armenia',
'Australia',
'Austria',
'Azerbaijan',
'Bahamas',
'Bahrain',
'Bangladesh',
'Barbados',
'Belarus',
'Belgium',
'Belize',
'Benin',
'Bhutan',
'Bolivia',
'Bosnia and Herzegovina',
'Botswana',
'Brazil',
'Brunei',
'Bulgaria',
'Burkina Faso',
'Burundi',
'Cambodia',
'Cameroon',
'Canada',
'Cape Verde',
'Central African Republic',
'Chad',
'Chile',
'China',
'Colombi',
'Comoros',
'Congo (Brazzaville)',
'Congo',
'Costa Rica',
"Cote d'Ivoire",
'Croatia',
'Cuba',
'Cyprus',
'Czech Republic',
'Denmark',
'Djibouti',
'Dominica',
'Dominican Republic',
'East Timor (Timor Timur)',
'Ecuador',
'Egypt',
'El Salvador',
'Equatorial Guinea',
'Eritrea',
'Estonia',
'Ethiopia',
'Fiji',
'Finland',
'France',
'Gabon',
'Gambia, The',
'Georgia',
'Germany',
'Ghana',
'Greece',
'Grenada',
'Guatemala',
'Guinea',
'Guinea-Bissau',
'Guyana',
'Haiti',
'Honduras',
'Hungary',
'Iceland',
'India',
'Indonesia',
'Iran',
'Iraq',
'Ireland',
'Israel',
'Italy',
'Jamaica',
'Japan',
'Jordan',
'Kazakhstan',
'Kenya',
'Kiribati',
'Korea, North',
'Korea, South',
'Kuwait',
'Kyrgyzstan',
'Laos',
'Latvia',
'Lebanon',
'Lesotho',
'Liberia',
'Libya',
'Liechtenstein',
'Lithuania',
'Luxembourg',
'Macedonia',
'Madagascar',
'Malawi',
'Malaysia',
'Maldives',
'Mali',
'Malta',
'Marshall Islands',
'Mauritania',
'Mauritius',
'Mexico',
'Micronesia',
'Moldova',
'Monaco',
'Mongolia',
'Morocco',
'Mozambique',
'Myanmar',
'Namibia',
'Nauru',
'Nepal',
'Netherlands',
'New Zealand',
'Nicaragua',
'Niger',
'Nigeria',
'Norway',
'Oman',
'Pakistan',
'Palau',
'Panama',
'Papua New Guinea',
'Paraguay',
'Peru',
'Philippines',
'Poland',
'Portugal',
'Qatar',
'Romania',
'Russia',
'Rwanda',
'Saint Kitts and Nevis',
'Saint Lucia',
'Saint Vincent',
'Samoa',
'San Marino',
'Sao Tome and Principe',
'Saudi Arabia',
'Senegal',
'Serbia and Montenegro',
'Seychelles',
'Sierra Leone',
'Singapore',
'Slovakia',
'Slovenia',
'Solomon Islands',
'Somalia',
'South Africa',
'Spain',
'Sri Lanka',
'Sudan',
'Suriname',
'Swaziland',
'Sweden',
'Switzerland',
'Syria',
'Taiwan',
'Tajikistan',
'Tanzania',
'Thailand',
'Togo',
'Tonga',
'Trinidad and Tobago',
'Tunisia',
'Turkey',
'Turkmenistan',
'Tuvalu',
'Uganda',
'Ukraine',
'United Arab Emirates',
'United Kingdom',
'United States',
'Uruguay',
'Uzbekistan',
'Vanuatu',
'Vatican City',
'Venezuela',
'Vietnam',
'Yemen',
'Zambia',
'Zimbabwe',
];

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,228 @@
"""
01_funcion.py
"""
import math
# Ejercicios: Nivel 1
# 1. Declara una función llamada add_two_numbers.
# Toma dos parámetros y devuelve la suma.
def add_two_numbers(a, b):
return a + b
print(f"La suma de los parámetros es igual a {add_two_numbers(2, 3)}")
# 2. El área de un círculo se calcula de la siguiente manera:
# área = π x r x r.
# Escribe una función que calcule area_of_circle.
def area_of_circle(r):
return math.pi * r * r
radio = 5
print(
f"El área del círculo con el radio {radio} es igual a {area_of_circle(radio)}")
# 3. Escribe una función llamada add_all_nums que tome
# un número arbitrario de argumentos y sume todos los argumentos.
# Verifica si todos los elementos de la lista son de tipo numérico.
# Si no lo son, proporciona un mensaje de retroalimentación razonable.
def add_all_nums(*args):
total = 0
for num in args:
if isinstance(num, (int, float)):
total += num
else:
return "No todos los elementos son numéricos"
return f"La suma de los parámetros es igual a {total}"
print(f"{add_all_nums(1, 2, 3, 4, '5')}")
# 4. La temperatura en °C se puede convertir a °F
# utilizando la siguiente fórmula:
# °F = (°C x 9/5) + 32.
# Escribe una función que convierta de °C a °F,
# convert_celsius_to_fahrenheit.
def convert_celsius_to_fahrenheit(celsius):
return (celsius * 9/5) + 32
temperatura = 36
print(
f"La temperatura de {temperatura} °C en fahrenheit es igual a {convert_celsius_to_fahrenheit(temperatura)}")
# 5. Escribe una función llamada check_season.
# Toma un parámetro de mes y devuelve la estación:
# Otoño, Invierno, Primavera o Verano.
def check_season(month):
if month in [12, 1, 2]:
return "Invierno"
elif month in [3, 4, 5]:
return "Primavera"
elif month in [6, 7, 8]:
return "Verano"
elif month in [9, 10, 11]:
return "Otoño"
else:
return "Mes no válido"
mes = 1
print(f"El mes {mes} es de {check_season(mes)}")
# 6. Escribe una función llamada calculate_slope
# que devuelva la pendiente de una ecuación lineal.
def calculate_slope(x1, y1, x2, y2):
return (y2 - y1) / (x2 - x1)
print(
f"La pendiente de la ecuación lineal es igual a {calculate_slope(2, 3, 6, 7)}")
# 7. La ecuación cuadrática se calcula de la siguiente manera: ax² + bx + c = 0.
# Escribe una función que calcule el conjunto de soluciones de una ecuación cuadrática, solve_quadratic_eqn.
def solve_quadratic_eqn(a, b, c):
discriminant = b**2 - 4*a*c
if discriminant > 0:
x1 = (-b + math.sqrt(discriminant)) / (2*a)
x2 = (-b - math.sqrt(discriminant)) / (2*a)
return (x1, x2)
elif discriminant == 0:
x1 = -b / (2*a)
return (x1,)
else:
return "No hay soluciones reales"
print(
f"Las soluciones de la ecuación cuadrática son {solve_quadratic_eqn(5, 8, 1)}")
# 8. Declara una función llamada print_list.
# Toma una lista como parámetro
# y imprime cada elemento de la lista.
def print_list(my_list):
for item in my_list:
print(f" - {item}")
lista_frutas = ["Manzana", "Pera", "Naranja", "Plátano", "Kiwi"]
print_list(lista_frutas)
# 9. Declara una función llamada reverse_list.
# Toma un arreglo como parámetro
# y devuelve el arreglo invertido (usa bucles).
def reverse_list(my_list):
reversed_list = []
i = len(my_list) - 1
while i >= 0:
reversed_list.append(my_list[i])
i -= 1
return reversed_list
lista_numeros = [1, 2, 3, 4, 5]
lista_letras = ["A", "B", "C"]
print(reverse_list(lista_numeros))
print(reverse_list(lista_letras))
# 10. Declara una función llamada
# capitalize_list_items.
# Toma una lista como parámetro
# y devuelve una lista de elementos en mayúsculas.
def capitalize_list_items(my_list):
return [item.upper() for item in my_list]
print(capitalize_list_items(lista_frutas))
# 11. Declara una función llamada add_item.
# Toma una lista y un parámetro de elemento.
# Devuelve una lista con el elemento agregado al final.
def add_item(my_list, item):
my_list.append(item)
return my_list
print(add_item(lista_frutas, "Melón"))
print(add_item(lista_numeros, 6))
# 12. Declara una función llamada remove_item.
# Toma una lista y un parámetro de elemento.
# Devuelve una lista con el elemento eliminado de ella.
def remove_item(my_list, item):
if item in my_list:
my_list.remove(item)
return my_list
print(remove_item(lista_frutas, "Pera"))
print(remove_item(lista_numeros, 2))
# 13. Declara una función llamada sum_of_numbers.
# Toma un número como parámetro
# y suma todos los números en ese rango.
def sum_of_numbers(n):
return sum(range(1, n+1))
print(sum_of_numbers(7))
# 14. Declara una función llamada sum_of_odds.
# Toma un número como parámetro
# y suma todos los números impares en ese rango.
def sum_of_odds(n):
sum = 0
for i in range(1, n+1, 2):
sum += i
return sum
print(sum_of_odds(7))
# 15. Declara una función llamada sum_of_even.
# Toma un número como parámetro
# y suma todos los números pares en ese rango.
def sum_of_even(n):
sum = 0
for i in range(2, n+1, 2):
sum += i
return sum
print(sum_of_even(7))

View File

@@ -0,0 +1,116 @@
"""
02_funcion.py
"""
# Ejercicios: Nivel 2
# 1. Declara una función llamada evens_and_odds.
# Toma un número entero positivo como parámetro
# y cuenta el número de pares e impares en ese número.
def evens_and_odds(n):
evens = 0
odds = 0
for i in range(1, n+1):
if i % 2 == 0:
evens += 1
else:
odds += 1
return f"El número de impares es {odds}.\nEl número de pares es {evens}."
print(evens_and_odds(101))
# 2. Llama a tu función factorial,
# toma un número entero como parámetro
# y devuelve el factorial de ese número.
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)
num_factorial = 5
print(f"El factorial de {num_factorial} es {factorial(num_factorial)}.")
# 3. Llama a tu función is_empty,
# toma un parámetro
# y verifica si está vacío o no.
def is_empty(item):
if not item:
return "La variable está vacía."
else:
return "La variable no está vacía."
print(is_empty(""))
# 4. Escribe diferentes funciones que tomen listas.
# Deben calcular la media, mediana, moda, rango,
# varianza y desviación estándar.
# Las funciones se llaman calculate_mean,
# calculate_median, calculate_mode,
# calculate_range, calculate_variance
# y calculate_std (desviación estándar).
def calculate_mean(my_list):
return sum(my_list) / len(my_list)
def calculate_median(my_list):
sorted_list = sorted(my_list)
n = len(my_list)
if n % 2 == 0:
return (sorted_list[n//2-1] + sorted_list[n//2]) / 2
else:
return sorted_list[n//2]
def calculate_mode(my_list):
freq_dict = {}
for num in my_list:
if num in freq_dict:
freq_dict[num] += 1
else:
freq_dict[num] = 1
max_freq = max(freq_dict.values())
mode_list = [num for num, freq in freq_dict.items() if freq == max_freq]
if len(mode_list) == len(my_list):
return None
elif len(mode_list) == 1:
return mode_list[0]
else:
return mode_list
def calculate_range(my_list):
return max(my_list) - min(my_list)
def calculate_variance(my_list):
mean = calculate_mean(my_list)
return sum([(x - mean)**2 for x in my_list]) / (len(my_list) - 1)
def calculate_std(my_list):
return calculate_variance(my_list) ** 0.5
my_list = [1, 2, 3, 4, 5, 5, 6, 7, 8, 9]
print(f"""De la lista {my_list} obtenemos:
- Media: {calculate_mean(my_list)}
- Mediana: {calculate_median(my_list)}
- Moda: {calculate_mode(my_list)}
- Rango: {calculate_range(my_list)}
- Varianza: {calculate_variance(my_list)}
- Desviación estándar: {calculate_std(my_list)}
""")

View File

@@ -0,0 +1,133 @@
"""
03_funcion.py
"""
import countries_data
# Ejercicios: Nivel 3
# 1. Escribe una función llamada is_prime
# que compruebe si un número es primo.
def is_prime(num):
if num <= 1:
return "No"
elif num == 2:
return ""
elif num % 2 == 0:
return "No"
else:
for i in range(3, int(num**0.5) + 1, 2):
if num % i == 0:
return "No"
return ""
numero_primo = 19
print(f"¿El número {numero_primo} es primo? {is_prime(numero_primo)}")
# 2. Escribe una función que compruebe
# si todos los elementos de una lista son únicos.
def are_elements_unique(my_list):
if len(my_list) == len(set(my_list)):
return ""
else:
return "No"
lista_elementos = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(
f"¿Los elementos de la lista {lista_elementos} son únicos? {are_elements_unique(lista_elementos)}")
# 3. Escribe una función que compruebe
# si todos los elementos de una lista
# son del mismo tipo de dato.
def are_elements_same_type(my_list):
first_type = type(my_list[0])
if not my_list:
return "Esto no es una lista."
elif all(isinstance(x, first_type) for x in my_list):
return ""
else:
return "No"
print(
f"¿Los elementos de la lista {lista_elementos} son del mismo tipo de dato? {are_elements_same_type(lista_elementos)}")
# 4. Escribe una función que compruebe
# si una variable proporcionada
# es una variable válida en Python.
def is_valid_variable_name(variable_name):
try:
exec(f"{variable_name} = None")
del locals()[variable_name]
return ""
except:
return "No"
print(
f"¿La variable 'variable_name' es válida? {is_valid_variable_name('variable_name')}")
# 5. Ve a la carpeta de datos
# y accede al archivo countries-data.py.
# Crea una función llamada
# most_spoken_languages_in_the_world.
# Debe devolver las 10 o 20 lenguas
# más habladas en orden descendente.
# Crea una función llamada
# most_populated_countries.
# Debe devolver los 10 o 20 países
# más poblados en orden descendente.
# Suponiendo que los datos están almacenados
# en una lista llamada "countries_data".
# Función para obtener las lenguas
# más habladas en el mundo.
def most_spoken_languages_in_the_world():
all_languages = []
for country in countries_data.countries_data:
all_languages.extend(country['languages'])
language_count = {}
for language in all_languages:
if language in language_count:
language_count[language] += 1
else:
language_count[language] = 1
sorted_languages = sorted(language_count.items(),
key=lambda x: x[1],
reverse=True)[:10]
language_list = [f"{i+1}. {language[0]}" for i,
language in enumerate(sorted_languages)]
return "\n".join(language_list)
print(most_spoken_languages_in_the_world())
# Función para obtener los países
# más poblados en el mundo.
def most_populated_countries():
sorted_countries = sorted(
countries_data.countries_data, key=lambda x: x['population'], reverse=True)[:10]
country_list = [f"{i+1}. {country['name']}" for i,
country in enumerate(sorted_countries)]
return "\n".join(country_list)
print(most_populated_countries())

View File

@@ -0,0 +1,94 @@
# Funciones
Documento original en inglés: [Functions](https://github.com/Asabeneh/30-Days-Of-Python/blob/master/11_Day_Functions/11_functions.md)
## Ejercicios
# Ejercicios: Nivel 1
1. Declara una función llamada `add_two_numbers`. Toma dos parámetros y devuelve la suma.
2. El área de un círculo se calcula de la siguiente manera: `área = π x r x r`. Escribe una función que calcule `area_of_circle`.
3. Escribe una función llamada `add_all_nums` que tome un número arbitrario de argumentos y sume todos los argumentos. Verifica si todos los elementos de la lista son de tipo numérico. Si no lo son, proporciona un mensaje de retroalimentación razonable.
4. La temperatura en °C se puede convertir a °F utilizando la siguiente fórmula: °F = (°C x 9/5) + 32. Escribe una función que convierta de °C a °F, `convert_celsius_to_fahrenheit`.
5. Escribe una función llamada `check_season`. Toma un parámetro de mes y devuelve la estación: Otoño, Invierno, Primavera o Verano.
6. Escribe una función llamada `calculate_slope` que devuelva la pendiente de una ecuación lineal.
7. La ecuación cuadrática se calcula de la siguiente manera: `ax² + bx + c = 0`. Escribe una función que calcule el conjunto de soluciones de una ecuación cuadrática, `solve_quadratic_eqn`.
8. Declara una función llamada `print_list`. Toma una lista como parámetro y imprime cada elemento de la lista.
9. Declara una función llamada `reverse_list`. Toma un arreglo como parámetro y devuelve el arreglo invertido (usa bucles).
```
print(reverse_list([1, 2, 3, 4, 5]))
# [5, 4, 3, 2, 1]
print(reverse_list1(["A", "B", "C"]))
# ["C", "B", "A"]
```
10. Declara una función llamada `capitalize_list_items`. Toma una lista como parámetro y devuelve una lista de elementos en mayúsculas.
11. Declara una función llamada `add_item`. Toma una lista y un parámetro de elemento. Devuelve una lista con el elemento agregado al final.
```
food_staff = ['Potato', 'Tomato', 'Mango', 'Milk'];
print(add_item(food_staff, 'Meat')) # ['Potato', 'Tomato', 'Mango', 'Milk','Meat'];
numbers = [2, 3, 7, 9];
print(add_item(numbers, 5)) [2, 3, 7, 9, 5]
```
12. Declara una función llamada `remove_item`. Toma una lista y un parámetro de elemento. Devuelve una lista con el elemento eliminado de ella.
```
food_staff = ['Potato', 'Tomato', 'Mango', 'Milk'];
print(remove_item(food_staff, 'Mango')) # ['Potato', 'Tomato', 'Milk'];
numbers = [2, 3, 7, 9];
print(remove_item(numbers, 3)) # [2, 7, 9]
```
13. Declara una función llamada `sum_of_numbers`. Toma un número como parámetro y suma todos los números en ese rango.
```
print(sum_of_numbers(5)) # 15
print(sum_all_numbers(10)) # 55
print(sum_all_numbers(100)) # 5050
```
14. Declara una función llamada `sum_of_odds`. Toma un número como parámetro y suma todos los números impares en ese rango.
15. Declara una función llamada `sum_of_even`. Toma un número como parámetro y suma todos los números pares en ese rango.
## Ejercicios: Nivel 2
1. Declara una función llamada `evens_and_odds`. Toma un número entero positivo como parámetro y cuenta el número de pares e impares en ese número.
```
print(evens_and_odds(100))
# The number of odds are 50.
# The number of evens are 51.
```
2. Llama a tu función `factorial`, toma un número entero como parámetro y devuelve el factorial de ese número.
3. Llama a tu función `is_empty`, toma un parámetro y verifica si está vacío o no.
4. Escribe diferentes funciones que tomen listas. Deben calcular la media, mediana, moda, rango, varianza y desviación estándar. Las funciones se llaman `calculate_mean`, `calculate_median`, `calculate_mode`, `calculate_range`, `calculate_variance` y `calculate_std` (desviación estándar).
## Ejercicios: Nivel 3
1. Escribe una función llamada `is_prime` que compruebe si un número es primo.
2. Escribe una función que compruebe si todos los elementos de una lista son únicos.
3. Escribe una función que compruebe si todos los elementos de una lista son del mismo tipo de dato.
4. Escribe una función que compruebe si una variable proporcionada es una variable válida en Python.
5. Ve a la carpeta de datos y accede al archivo countries-data.py.
- Crea una función llamada `most_spoken_languages_in_the_world`. Debe devolver las 10 o 20 lenguas más habladas en el mundo en orden descendente.
- Crea una función llamada `most_populated_countries`. Debe devolver los 10 o 20 países más poblados en orden descendente.
[<< Day 10](../10_Bucles/README.md) | [Day 12 >>](../12_Módulos/README.md)

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,156 @@
"""
01_modulos.py
"""
import random
import string
# Ejercicios: Nivel 1
# 1. Escribe una función que genere
# un identificador de usuario aleatorio
# de seis dígitos/caracteres.
def random_user_id():
contra = ''.join(random.choices(
string.ascii_lowercase + string.digits, k=6))
return contra
print(random_user_id())
# 2. Modifica la tarea anterior.
# Declara una función llamada user_id_gen_by_user.
# No toma parámetros,
# pero toma dos entradas utilizando input().
# Una de las entradas es el número de caracteres
# y la segunda entrada es el número de IDs
# que se supone que deben generarse.
# ```
def user_id_gen_by_user():
n = int(input("Ingrese el número de caracteres: "))
m = int(input("Ingrese el número de IDs a generar: "))
user_ids = []
for i in range(m):
user_id = ''.join(random.choices(
string.ascii_lowercase + string.digits, k=n))
user_ids.append(user_id.upper())
return '\n'.join(user_ids)
print(user_id_gen_by_user())
# 3. Escribe una función llamada rgb_color_gen
# que generará colores RGB
# (3 valores que van desde 0 hasta 255 cada uno).
def rgb_color_gen():
r = random.randint(0, 255)
g = random.randint(0, 255)
b = random.randint(0, 255)
return f"rgb({r},{g},{b})"
print(rgb_color_gen())
# ### Ejercicios: Nivel 2
# 1. Escribe una función llamada
# list_of_hexa_colors que devuelva
# cualquier cantidad de colores hexadecimales
# en una lista (seis números hexadecimales escritos después del #).
def list_of_hexa_colors(n):
hexa_colors = []
for i in range(n):
hexa_color = ''.join([random.choice('0123456789abcdef')
for j in range(6)])
hexa_colors.append(f"#{hexa_color}")
return hexa_colors
print(list_of_hexa_colors(5))
# 2. Escribe una función llamada
# list_of_rgb_colors que devuelva
# cualquier cantidad de colores RGB
# en una lista.
def list_of_rgb_colors(n):
rgb_colors = []
for i in range(n):
r = random.randint(0, 255)
g = random.randint(0, 255)
b = random.randint(0, 255)
rgb_colors.append(f"rgb({r},{g},{b})")
return rgb_colors
print(list_of_rgb_colors(5))
# 3. Escribe una función llamada
# generate_colors que pueda generar
# cualquier cantidad de colores
# hexadecimales o RGB.
def generate_colors():
color_type = input("¿hexa o rgb? ")
n = int(input("¿Cuántos colores? "))
colors = []
if color_type == 'hexa':
for i in range(n):
hexa_color = ''.join(
[random.choice('0123456789abcdef') for j in range(6)])
colors.append(f"#{hexa_color}")
elif color_type == 'rgb':
for i in range(n):
r = random.randint(0, 255)
g = random.randint(0, 255)
b = random.randint(0, 255)
colors.append(f"rgb({r},{g},{b})")
return colors
print(generate_colors())
# ### Ejercicios: Nivel 3
# 1. Llama a tu función shuffle_list,
# toma una lista como parámetro
# y devuelve una lista mezclada.
def shuffle_list(lst):
random.shuffle(lst)
return lst
my_list = list(range(50))
print(shuffle_list(my_list))
# 2. Escribe una función
# que devuelva una matriz
# de siete números aleatorios
# en un rango de 0-9.
# Todos los números deben ser únicos.
def unique_random_numbers():
numbers = []
while len(numbers) < 7:
number = random.randint(0, 9)
if number not in numbers:
numbers.append(number)
return numbers
print(unique_random_numbers())

View File

@@ -0,0 +1,68 @@
# Módulos
Documento original en inglés: [Modules](https://github.com/Asabeneh/30-Days-Of-Python/blob/master/12_Day_Modules/12_modules.md)
## Ejercicios
### Ejercicios: Nivel 1
1. Escribe una función que genere un identificador de usuario aleatorio de seis dígitos/caracteres.
```python
print(random_user_id())
# '1ee33d'
```
2. Modifica la tarea anterior. Declara una función llamada user_id_gen_by_user. No toma parámetros, pero toma dos entradas utilizando input(). Una de las entradas es el número de caracteres y la segunda entrada es el número de IDs que se supone que deben generarse.
```
print(user_id_gen_by_user()) # Entrada de usuario: 5 5
# Salida:
# kcsy2
# SMFYb
# bWmeq
# ZXOYh
# 2Rgxf
print(user_id_gen_by_user()) # Entrada de usuario: 16 5
# Salida:
# 1GCSgPLMaBAVQZ26
# YD7eFwNQKNs7qXaT
# ycArC5yrRupyG00S
# UbGxOFI7UXSWAyKN
# dIV0SSUTgAdKwStr
```
3. Escribe una función llamada rgb_color_gen que generará colores RGB (3 valores que van desde 0 hasta 255 cada uno).
```
print(rgb_color_gen())
# 'rgb(125,244,255)' - la salida debe estar en esta forma
```
### Ejercicios: Nivel 2
1. Escribe una función llamada list_of_hexa_colors que devuelva cualquier cantidad de colores hexadecimales en una lista (seis números hexadecimales escritos después del #). El sistema numérico hexadecimal está compuesto por 16 símbolos, del 0 al 9 y las primeras 6 letras del alfabeto, de la a a la f. Mira el ejercicio 6 para ejemplos de salida.
2. Escribe una función llamada list_of_rgb_colors que devuelva cualquier cantidad de colores RGB en una lista.
3. Escribe una función llamada generate_colors que pueda generar cualquier cantidad de colores hexadecimales o RGB.
```
generate_colors('hexa', 3)
# ['#a3e12f','#03ed55','#eb3d2b']
generate_colors('hexa', 1)
# ['#b334ef']
generate_colors('rgb', 3)
# ['rgb(5, 55, 175','rgb(50, 105, 100','rgb(15, 26, 80']
generate_colors('rgb', 1)
# ['rgb(33,79, 176)']
```
Ejercicios: Nivel 3
1. Llama a tu función shuffle_list, toma una lista como parámetro y devuelve una lista mezclada.
2. Escribe una función que devuelva una matriz de siete números aleatorios en un rango de 0-9. Todos los números deben ser únicos.
[Solución](01_modulos.py)
[<< Day 11](../11_Funciones/README.md) | [Day 13 >>](../13_Comprensión_de_listas/README.md)

View File

@@ -0,0 +1,129 @@
"""
01_compr_listas.py
"""
# Ejercicios: Nivel 1
# 1. Filtra solo los números negativos y cero
# en la lista usando una comprensión de lista.
numbers = [-4, -3, -2, -1, 0, 2, 4, 6]
filtered_numbers = [num for num in numbers if num <= 0]
print(filtered_numbers)
print("")
# 2. Aplana la siguiente lista de listas de listas
# a una lista unidimensional:
list_of_lists = [
[[1, 2, 3]],
[[4, 5, 6]],
[[7, 8, 9]]
]
flattened_list = [
num for sublist in list_of_lists for subsublist in sublist for num in subsublist]
print(flattened_list)
print("")
# 3. Usando una comprensión de lista,
# crea la siguiente lista de tuplas:
tuples_list = [
(i, 1, i, i**2, i**3, i**4, i**5) for i in range(11)
]
for tpl in tuples_list:
print(str(tpl).replace(", ", ","))
print("")
# 4. Aplana la siguiente lista
# a una nueva lista:
countries = [
[
('Finland', 'Helsinki')
],
[
('Sweden', 'Stockholm')
],
[
('Norway', 'Oslo')
]
]
flattened_countries = [
[
country.upper(),
country[:3].upper(),
city.upper()
]
for sublist in countries for country,
city in sublist
]
for sublist in flattened_countries:
print(sublist)
print("")
# 5. Cambia la siguiente lista
# a una lista de diccionarios:
countries = [
[('Finland', 'Helsinki')], [
('Sweden', 'Stockholm')],
[('Norway', 'Oslo')]
]
dict_list = [
{'country': country, 'city': city}
for sublist in countries for country,
city in sublist
]
for dct in dict_list:
print(dct)
print("")
# 6. Cambia la siguiente lista de listas
# a una lista de cadenas concatenadas:
names = [
[('Asabeneh', 'Yetayeh')],
[('David', 'Smith')],
[('Donald', 'Trump')],
[('Bill', 'Gates')]
]
concatenated_names = [' '.join(name) for sublist in names for name in sublist]
print(concatenated_names)
print("")
# 7. Escribe una función lambda
# que pueda resolver una pendiente
# o una ordenada al origen de funciones lineales.
# La función lambda toma dos argumentos: x y m, donde x es la variable independiente y m es la pendiente.
# La función devuelve la ordenada al origen de la función lineal.
def linear_function(x, m):
return -m * x
x = imn
m = 2
result = linear_function(x, m)
print(
f"Para x = {x} y m = {m}, el resultado de la función lineal es {result}.")

View File

@@ -0,0 +1,68 @@
# Comprensión de listas
Documento original en inglés: [List comprehension](https://github.com/Asabeneh/30-Days-Of-Python/blob/master/13_Day_List_comprehension/13_list_comprehension.md)
## Ejercicios
### Ejercicios: Nivel 1
1. Filtra solo los números negativos y cero en la lista usando una comprensión de lista.
```python
numbers = [-4, -3, -2, -1, 0, 2, 4, 6]
```
2. Aplana la siguiente lista de listas de listas a una lista unidimensional:
```
list_of_lists =[[[1, 2, 3]], [[4, 5, 6]], [[7, 8, 9]]]
# Resultado: [1, 2, 3, 4, 5, 6, 7, 8, 9]
```
3. Usando una comprensión de lista, crea la siguiente lista de tuplas:
```
[(0, 1, 0, 0, 0, 0, 0),
(1, 1, 1, 1, 1, 1, 1),
(2, 1, 2, 4, 8, 16, 32),
(3, 1, 3, 9, 27, 81, 243),
(4, 1, 4, 16, 64, 256, 1024),
(5, 1, 5, 25, 125, 625, 3125),
(6, 1, 6, 36, 216, 1296, 7776),
(7, 1, 7, 49, 343, 2401, 16807),
(8, 1, 8, 64, 512, 4096, 32768),
(9, 1, 9, 81, 729, 6561, 59049),
(10, 1, 10, 100, 1000, 10000, 100000)]
```
4. Aplana la siguiente lista a una nueva lista:
```
countries = [[('Finland', 'Helsinki')], [('Sweden', 'Stockholm')], [('Norway', 'Oslo')]]
# Resultado:
[['FINLAND', 'FIN', 'HELSINKI'],
['SWEDEN', 'SWE', 'STOCKHOLM'],
['NORWAY', 'NOR', 'OSLO']]
```
5. Cambia la siguiente lista a una lista de diccionarios:
```
countries = [[('Finland', 'Helsinki')], [('Sweden', 'Stockholm')], [('Norway', 'Oslo')]]
# Resultado:
[{'country': 'Finland', 'city': 'Helsinki'},
{'country': 'Sweden', 'city': 'Stockholm'},
{'country': 'Norway', 'city': 'Oslo'}]
```
6. Cambia la siguiente lista de listas a una lista de cadenas concatenadas:
```
names = [[('Asabeneh', 'Yetayeh')], [('David', 'Smith')], [('Donald', 'Trump')], [('Bill', 'Gates')]]
# Resultado: ['Asabeneh Yetayeh', 'David Smith', 'Donald Trump', 'Bill Gates']
```
7. Escribe una función lambda que pueda resolver una pendiente o una ordenada al origen de funciones lineales.
[Solución](01_compr_listas.py)
[<< Day 12](../12_Módulos/README.md) | [Day 14 >>](../14_Funciones_de_orden_superior/README.md)

View File

@@ -0,0 +1,105 @@
"""
01_func_sup.py
"""
# Ejercicios: Nivel 1
# 1. Explica la diferencia entre map, filter y reduce.
# map, filter y reduce son funciones integradas en Python
# que se utilizan para procesar y transformar datos.
# map toma una función y una secuencia
# y aplica la función a cada elemento de la secuencia,
# devolviendo una nueva secuencia con los resultados.
# filter toma una función y una secuencia
# y devuelve una nueva secuencia
# que contiene solo los elementos de la secuencia original
# para los cuales la función devuelve True.
# reduce toma una función y una secuencia
# y aplica la función a los elementos de la secuencia
# de izquierda a derecha, reduciendo la secuencia a un solo valor.
# 2. Explica la diferencia entre función
# de orden superior, cierre y decorador.
# Una función de orden superior es una función
# que toma una o más funciones como argumentos
# y/o devuelve una función como resultado.
# Un cierre es una función
# que recuerda el estado
# de su entorno léxico cuando se define
# y puede acceder a ese estado
# incluso cuando se llama en un entorno diferente.
# Un decorador es una función
# que toma otra función
# y extiende o modifica su comportamiento
# sin cambiar su código fuente.
# 3. Define una función de llamada antes de map, filter o reduce,
# mira los ejemplos.
# map
from functools import reduce
def double(x):
return x * 2
numbers = [1, 2, 3, 4, 5]
doubled_numbers = list(map(double, numbers))
print(doubled_numbers)
# filter
def is_even(x):
return x % 2 == 0
even_numbers = list(filter(is_even, numbers))
print(even_numbers)
# reduce
def add(x, y):
return x + y
sum = reduce(add, numbers)
print(sum)
# 4. Usa un bucle for para imprimir cada país
# en la lista de países.
countries = ["Spain", "France", "Germany", "Italy"]
for country in countries:
print(country)
# 5. Usa un bucle for para imprimir cada nombre
# en la lista de nombres.
names = ["Alice", "Bob", "Charlie", "David"]
for name in names:
print(name)
# 6. Usa un bucle for para imprimir cada número
# en la lista de números.
for number in numbers:
print(number)

View File

@@ -0,0 +1,195 @@
"""
02_func_sup.py
"""
from functools import reduce
import countries
# Ejercicios: Nivel 2
# 1. Usa map para crear una nueva lista
# cambiando cada país a mayúsculas
# en la lista de países.
upper_countries = list(map(str.upper, countries.countries))
print(upper_countries)
print()
# 2. Usa map para crear una nueva lista
# cambiando cada número por su cuadrado
# en la lista de números.
numbers = [1, 2, 3, 4, 5]
squared_numbers = list(map(lambda x: x ** 2, numbers))
print(squared_numbers)
print()
# 3. Usa map para cambiar
# cada nombre a mayúsculas
# en la lista de nombres.
names = ["Alice", "Bob", "Charlie", "David"]
upper_names = list(map(str.upper, names))
print(upper_names)
print()
# 4. Usa filter para filtrar
# los países que contengan 'land'.
land_countries = list(filter(lambda x: "land" in x, countries.countries))
print(land_countries)
print()
# 5. Usa filter para filtrar los países
# que tengan exactamente seis caracteres.
six_letter_countries = list(filter(lambda x: len(x) == 6, countries.countries))
print(six_letter_countries)
print()
# 6. Usa filter para filtrar los países
# que contengan seis letras
# o más en la lista de países.
long_countries = list(filter(lambda x: len(x) >= 6, countries.countries))
print(long_countries)
print()
# 7. Usa filter para filtrar los países
# que comiencen con 'E'.
e_countries = list(filter(lambda x: x.startswith("E"), countries.countries))
print(e_countries)
print()
# 8. Encadena dos o más iteradores de lista
# (por ejemplo,
# arr.map(callback).filter(callback).reduce(callback)).
numbers = [1, 2, 3, 4, 5]
result = list(map(lambda x: x ** 2, filter(lambda x: x % 2 == 0, numbers)))
print(result)
print()
# 9. Declara una función llamada get_string_lists
# que tome una lista como parámetro
# y luego devuelva una lista que contenga
# solo elementos de tipo cadena.
def get_string_lists(lst):
return list(filter(lambda x: isinstance(x, str), lst))
mixed_list = [1, "hello", 2, "world", 3]
string_list = get_string_lists(mixed_list)
print(string_list)
print()
# 10. Usa reduce para sumar todos los números
# en la lista de números.
numbers = [1, 2, 3, 4, 5]
sum = reduce(lambda x, y: x + y, numbers)
print(sum)
print()
# 11. Usa reduce para concatenar todos los países
# y producir la siguiente oración:
# Estonia, Finlandia, Suecia, Dinamarca, Noruega e Islandia son países del norte de Europa.
sentence = reduce(lambda x, y: x + ", " + y, countries.countries)
print(sentence + " son países del norte de Europa.")
print()
# 12. Declara una función llamada categorize_countries
# que devuelva una lista de países
# con algún patrón común de countries.py
def categorize_countries():
patterns = ["land", "ia", "island", "stan"]
categorized_countries = []
for pattern in patterns:
matching_countries = list(
filter(lambda x: pattern in x.lower(), countries.countries))
categorized_countries.append(matching_countries)
return categorized_countries
print(categorize_countries())
print()
# 13. Crea una función que devuelva un diccionario,
# donde las claves sean las letras iniciales de los países
# y los valores sean la cantidad de nombres de países
# que comienzan con esa letra.
def count_countries_by_initial():
counts = {}
for country in countries.countries:
initial = country[0]
if initial in counts:
counts[initial] += 1
else:
counts[initial] = 1
return counts
print(count_countries_by_initial())
print()
# 14. Declara una función llamada get_first_ten_countries
# que devuelva una lista de los primeros diez países
# de la lista de países.
def get_first_ten_countries():
return countries.countries[:10]
print(get_first_ten_countries())
print()
# 15. Declara una función llamada get_last_ten_countries
# que devuelva los últimos diez países
# en la lista de países.
def get_last_ten_countries():
return countries.countries[-10:]
print(get_last_ten_countries())
print()

View File

@@ -0,0 +1,61 @@
"""
03_func_sup.py
"""
import countries_data
from collections import Counter
# Ejercicios: Nivel 3
# 1. Usa el archivo [countries_data.py](https://github.com/Asabeneh/30-Days-Of-Python/blob/master/data/countries-data.py) y sigue las siguientes tareas:
# - Ordena los países por nombre, capital y población.
sorted_by_name = sorted(countries_data.countries,
key=lambda country: country['name'])
sorted_by_capital = sorted(
countries_data.countries,
key=lambda country: country['capital']
)
sorted_by_population = sorted(
countries_data.countries,
key=lambda country: country['population'],
reverse=True
)
# Filtra los diez idiomas más hablados por ubicación
all_languages = []
for country in countries_data.countries:
all_languages.extend(country['languages'])
# Calcula las frecuencias de cada idioma
language_counts = Counter(all_languages)
# Obtiene los diez idiomas más hablados
top_10_languages = language_counts.most_common(10)
# Filtra los diez países más poblados
top_10_population = sorted(
countries_data.countries, key=lambda country: country['population'], reverse=True)[:10]
# Imprime los resultados
print("## Países ordenados por nombre:")
for country in sorted_by_name:
print(country['name'])
print("\n## Países ordenados por capital:")
for country in sorted_by_capital:
print(country['name'], "-", country['capital'])
print("\n## Países ordenados por población:")
for country in sorted_by_population:
print(country['name'], "-", country['population'])
print("\n## Los diez idiomas más hablados por ubicación:")
for language, count in top_10_languages:
print(language, "-", count)
print("\n## Los diez países más poblados:")
for country in top_10_population:
print(country['name'], "-", country['population'])

View File

@@ -0,0 +1,53 @@
# Funciones de Orden Superior
Documento original en inglés: [Higher Order Functions](https://github.com/Asabeneh/30-Days-Of-Python/blob/master/14_Day_Higher_order_functions/14_higher_order_functions.md)
## Ejercicios
```
countries = ['Estonia', 'Finlandia', 'Suecia', 'Dinamarca', 'Noruega', 'Islandia']
names = ['Asabeneh', 'Lidiya', 'Ermias', 'Abraham']
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
```
### Ejercicios: Nivel 1
1. Explica la diferencia entre map, filter y reduce.
2. Explica la diferencia entre función de orden superior, cierre y decorador.
3. Define una función de llamada antes de map, filter o reduce, mira los ejemplos.
4. Usa un bucle for para imprimir cada país en la lista de países.
5. Usa un bucle for para imprimir cada nombre en la lista de nombres.
6. Usa un bucle for para imprimir cada número en la lista de números.
[Solución](01_func_sup.py)
### Ejercicios: Nivel 2
1. Usa map para crear una nueva lista cambiando cada país a mayúsculas en la lista de países.
2. Usa map para crear una nueva lista cambiando cada número por su cuadrado en la lista de números.
3. Usa map para cambiar cada nombre a mayúsculas en la lista de nombres.
4. Usa filter para filtrar los países que contengan 'land'.
5. Usa filter para filtrar los países que tengan exactamente seis caracteres.
6. Usa filter para filtrar los países que contengan seis letras o más en la lista de países.
7. Usa filter para filtrar los países que comiencen con 'E'.
8. Encadena dos o más iteradores de lista (por ejemplo, arr.map(callback).filter(callback).reduce(callback)).
9. Declara una función llamada get_string_lists que tome una lista como parámetro y luego devuelva una lista que contenga solo elementos de tipo cadena.
10. Usa reduce para sumar todos los números en la lista de números.
11. Usa reduce para concatenar todos los países y producir la siguiente oración: Estonia, Finlandia, Suecia, Dinamarca, Noruega e Islandia son países del norte de Europa.
12. Declara una función llamada categorize_countries que devuelva una lista de países con algún patrón común (puedes encontrar la [lista de países](https://github.com/Asabeneh/30-Days-Of-Python/blob/master/data/countries.py) en este repositorio como countries.js(eg 'land', 'ia', 'island', 'stan')).
13. Crea una función que devuelva un diccionario, donde las claves sean las letras iniciales de los países y los valores sean la cantidad de nombres de países que comienzan con esa letra.
14. Declara una función llamada get_first_ten_countries que devuelva una lista de los primeros diez países de la lista de países.
15. Declara una función llamada get_last_ten_countries que devuelva los últimos diez países en la lista de países.
[Solución](02_func_sup.py)
### Ejercicios: Nivel 3
1. Usa el archivo [countries_data.py](https://github.com/Asabeneh/30-Days-Of-Python/blob/master/data/countries-data.py) y sigue las siguientes tareas:
- Ordena los países por nombre, capital y población.
- Filtra los diez idiomas más hablados por ubicación.
- Filtra los diez países más poblados.
[Solución](03_func_sup.py)
[<< Day 13](../13_Comprensión_de_listas/README.md) | [Day 15 >>](../15_Errores_de_tipo_en_Python/README.md)

View File

@@ -0,0 +1,195 @@
countries = [
'Afghanistan',
'Albania',
'Algeria',
'Andorra',
'Angola',
'Antigua and Barbuda',
'Argentina',
'Armenia',
'Australia',
'Austria',
'Azerbaijan',
'Bahamas',
'Bahrain',
'Bangladesh',
'Barbados',
'Belarus',
'Belgium',
'Belize',
'Benin',
'Bhutan',
'Bolivia',
'Bosnia and Herzegovina',
'Botswana',
'Brazil',
'Brunei',
'Bulgaria',
'Burkina Faso',
'Burundi',
'Cambodia',
'Cameroon',
'Canada',
'Cape Verde',
'Central African Republic',
'Chad',
'Chile',
'China',
'Colombi',
'Comoros',
'Congo (Brazzaville)',
'Congo',
'Costa Rica',
"Cote d'Ivoire",
'Croatia',
'Cuba',
'Cyprus',
'Czech Republic',
'Denmark',
'Djibouti',
'Dominica',
'Dominican Republic',
'East Timor (Timor Timur)',
'Ecuador',
'Egypt',
'El Salvador',
'Equatorial Guinea',
'Eritrea',
'Estonia',
'Ethiopia',
'Fiji',
'Finland',
'France',
'Gabon',
'Gambia, The',
'Georgia',
'Germany',
'Ghana',
'Greece',
'Grenada',
'Guatemala',
'Guinea',
'Guinea-Bissau',
'Guyana',
'Haiti',
'Honduras',
'Hungary',
'Iceland',
'India',
'Indonesia',
'Iran',
'Iraq',
'Ireland',
'Israel',
'Italy',
'Jamaica',
'Japan',
'Jordan',
'Kazakhstan',
'Kenya',
'Kiribati',
'Korea, North',
'Korea, South',
'Kuwait',
'Kyrgyzstan',
'Laos',
'Latvia',
'Lebanon',
'Lesotho',
'Liberia',
'Libya',
'Liechtenstein',
'Lithuania',
'Luxembourg',
'Macedonia',
'Madagascar',
'Malawi',
'Malaysia',
'Maldives',
'Mali',
'Malta',
'Marshall Islands',
'Mauritania',
'Mauritius',
'Mexico',
'Micronesia',
'Moldova',
'Monaco',
'Mongolia',
'Morocco',
'Mozambique',
'Myanmar',
'Namibia',
'Nauru',
'Nepal',
'Netherlands',
'New Zealand',
'Nicaragua',
'Niger',
'Nigeria',
'Norway',
'Oman',
'Pakistan',
'Palau',
'Panama',
'Papua New Guinea',
'Paraguay',
'Peru',
'Philippines',
'Poland',
'Portugal',
'Qatar',
'Romania',
'Russia',
'Rwanda',
'Saint Kitts and Nevis',
'Saint Lucia',
'Saint Vincent',
'Samoa',
'San Marino',
'Sao Tome and Principe',
'Saudi Arabia',
'Senegal',
'Serbia and Montenegro',
'Seychelles',
'Sierra Leone',
'Singapore',
'Slovakia',
'Slovenia',
'Solomon Islands',
'Somalia',
'South Africa',
'Spain',
'Sri Lanka',
'Sudan',
'Suriname',
'Swaziland',
'Sweden',
'Switzerland',
'Syria',
'Taiwan',
'Tajikistan',
'Tanzania',
'Thailand',
'Togo',
'Tonga',
'Trinidad and Tobago',
'Tunisia',
'Turkey',
'Turkmenistan',
'Tuvalu',
'Uganda',
'Ukraine',
'United Arab Emirates',
'United Kingdom',
'United States',
'Uruguay',
'Uzbekistan',
'Vanuatu',
'Vatican City',
'Venezuela',
'Vietnam',
'Yemen',
'Zambia',
'Zimbabwe',
]

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,11 @@
# Errores de tipo en Python
Documento original en inglés: [Python Type Errors](https://github.com/Asabeneh/30-Days-Of-Python/blob/master/15_Day_Python_type_errors/15_python_type_errors.md)
## Ejercicios
1. Abre tu shell interactivo de Python y prueba todos los ejemplos cubiertos en esta [sección](https://github.com/Asabeneh/30-Days-Of-Python/blob/master/15_Day_Python_type_errors/15_python_type_errors.md).
Ánimo! 💪
[<< Day 14](../14_Funciones_de_orden_superior/README.md) | [Day 16 >>](../16_Fecha_y_hora_en_Python/README.md)

View File

@@ -0,0 +1,96 @@
"""
01_time.py
"""
from datetime import datetime
import locale
# 1. Obtener el día actual,
# mes, año, hora, minuto
# y marca de tiempo actual
# desde el módulo datetime.
now = datetime.now()
print("Día actual:", now.day)
print("Mes actual:", now.month)
print("Año actual:", now.year)
print("Hora actual:", now.hour)
print("Minuto actual:", now.minute)
print("Marca de tiempo actual:", now)
print()
# 2. Formatear la fecha actual
# utilizando este formato:
# "%m/%d/%Y, %H:%M:%S".
formatted_now = now.strftime("%m/%d/%Y, %H:%M:%S")
print("Fecha formateada:", formatted_now)
print()
# 3. Cambiar la cadena de tiempo
# "5 de diciembre de 2019"
# a un objeto de tiempo.
# Establecer el idioma en español
# porque sino no funciona,
# el idioma por defecto es el inglés.
locale.setlocale(locale.LC_ALL, 'es_ES')
time_str = "05 de diciembre de 2019"
time_obj = datetime.strptime(time_str, "%d de %B de %Y")
print("Objeto de tiempo:", time_obj)
print()
# 4. Calcular la diferencia de tiempo entre ahora y el Año Nuevo.
new_year = datetime(2022, 1, 1)
time_diff = new_year - now
print("Diferencia de tiempo hasta el Año Nuevo:\n", time_diff)
print()
# 5. Calcular la diferencia de tiempo entre
# el 1 de enero de 1970 y ahora.
epoch = datetime(1970, 1, 1)
time_diff = now - epoch
print(
"Diferencia de tiempo desde el 1 de enero de 1970 hasta ahora:\n",
time_diff
)
print()
# 6. Ejemplos de uso del módulo datetime:
# - Análisis de series temporales.
# Lista de fechas
fechas = ["2023-09-01", "2023-09-15", "2023-09-30"]
# Convertir las fechas a objetos datetime
fechas_dt = [
datetime.strptime(fecha, "%Y-%m-%d") for fecha in fechas
]
print()
# Calcular la diferencia entre fechas
diferencia = fechas_dt[-1] - fechas_dt[0]
print("Diferencia de tiempo:", diferencia)
# - Obtener una marca de tiempo de cualquier actividad en una aplicación.
# Registra la actividad
actividad = "Usuario inició sesión"
tiempo_actividad = datetime.now()
print(f"{actividad} a las {tiempo_actividad}")
print()
# - Publicar entradas en un blog.
# Contenido de la entrada del blog
contenido = "Hoy estoy publicando mi primera entrada en el blog."
# Fecha y hora de publicación
# Año, mes, día, hora, minuto
fecha_publicacion = datetime(2023, 9, 29, 15, 30)
# Publicar la entrada
print(f"Entrada publicada el {fecha_publicacion}:\n{contenido}")
print()

View File

@@ -0,0 +1,19 @@
# Fecha y Hora en Python
Documento original en inglés: [Python Date time](https://github.com/Asabeneh/30-Days-Of-Python/blob/master/16_Day_Python_date_time/16_python_datetime.md)
## Ejercicios
1. Obtén el día actual, mes, año, hora, minuto y marca de tiempo actual desde el módulo datetime.
2. Formatea la fecha actual utilizando este formato: "%m/%d/%Y, %H:%M:%S".
3. Hoy es 5 de diciembre de 2019. Cambia esta cadena de tiempo a un objeto de tiempo.
4. Calcula la diferencia de tiempo entre ahora y el Año Nuevo.
5. Calcula la diferencia de tiempo entre el 1 de enero de 1970 y ahora.
6. Piensa para qué puedes usar el módulo datetime. Ejemplos:
- Análisis de series temporales.
- Obtener una marca de tiempo de cualquier actividad en una aplicación.
- Publicar entradas en un blog.
[Solución](01_time.py)
[<< Day 15](../15_Errores_de_tipo_en_Python/README.md) | [Day 17 >>](../17_Manejo_de_excepciones/README.md)

View File

@@ -0,0 +1,31 @@
"""
01_exceptions.py
"""
# 1. Desempaca los cinco primeros países
# y almacénalos en una variable
# llamada 'nordic_countries',
# almacena 'Estonia' y 'Russia'
# en variables 'es' y 'ru'
# respectivamente.
names = [
'Finland',
'Sweden',
'Norway',
'Denmark',
'Iceland',
'Estonia',
'Russia'
]
nordic_countries = names[:5]
es, ru = names[-2:]
for country in nordic_countries:
print(country)
print(f"\n{es}\n\n{ru}\n ")
print("\U0001F604")

View File

@@ -0,0 +1,15 @@
# Manejo de excepciones
Documento original en inglés: [Exception handling](https://github.com/Asabeneh/30-Days-Of-Python/blob/master/17_Day_Exception_handling/17_exception_handling.md)
## Ejercicios
```
names = ['Finland', 'Sweden', 'Norway', 'Denmark', 'Iceland', 'Estonia', 'Russia'].
```
1. Desempaca los cinco primeros países y almacénalos en una variable llamada 'nordic_countries', almacena 'Estonia' y 'Russia' en variables 'es' y 'ru' respectivamente.
[Solución](01_exceptions.py)
[<< Day 16](../16_Fecha_y_hora_en_Python/README.md) | [Day 18 >>](../18_Expresiones_regulares/README.md)

View File

@@ -0,0 +1,124 @@
"""
01_regex.py
"""
import re
# Ejercicios: Nivel 1
# 1. ¿Cuál es la palabra más frecuente en el siguiente párrafo?
paragraph = 'I love teaching. If you do not love teaching what else can you love. I love Python if you do not love something which can give you all the capabilities to develop an application what else can you love.'
# Convertimos el párrafo a minúsculas
paragraph = paragraph.lower()
# Separamos el párrafo en palabras
words = paragraph.split()
# Creamos un diccionario para contar la frecuencia de cada palabra
word_freq = {}
for word in words:
if word in word_freq:
word_freq[word] += 1
else:
word_freq[word] = 1
# Encontramos la palabra más frecuente
most_freq_word = max(word_freq, key=word_freq.get)
print("La palabra más frecuente es:", most_freq_word)
# 2. La posición de algunas partículas
# en el eje x horizontal son - 12, -4, -3 y - 1
# en la dirección negativa,
# 0 en el origen,
# 4 y 8 en la dirección positiva.
# Extrae estos números de todo el texto
# y encuentra la distancia entre
# las dos partículas más lejanas.
text = "La posición de algunas partículas en el eje x horizontal son -12, -4, -3 y -1 en la dirección negativa, 0 en el origen, 4 y 8 en la dirección positiva."
# Extraemos los números del texto
numbers = re.findall(r'-?\d+', text)
# Convertimos los números a enteros
numbers = [int(num) for num in numbers]
# Encontramos la distancia entre las dos partículas más lejanas
distance = max(numbers) - min(numbers)
print("La distancia entre las dos partículas más lejanas es:", distance)
# Ejercicios: Nivel 2
# 1. Escribe un patrón que identifique
# si una cadena es una variable válida en Python.
# Definimos una función que verifica si una cadena es una variable válida en Python
def is_valid_variable(variable):
pattern = r'^[a-zA-Z_]\w*$'
if bool(re.match(pattern, variable)):
return f"La variable {variable} es válida"
else:
return f"La variable {variable} no es válida"
# Ejemplos de variables válidas e inválidas
valid_variables = ['my_var', 'myVar', '_my_var', 'myVar123', 'my_var_123']
invalid_variables = ['123myvar', 'my-var', 'my var', 'my$var']
# Verificamos si las variables son válidas o no
for variable in valid_variables:
print(variable, is_valid_variable(variable))
for variable in invalid_variables:
print(variable, is_valid_variable(variable))
# Ejercicios: Nivel 3
# 1. Limpia el siguiente texto. Después de limpiarlo, cuenta las tres palabras más frecuentes en la cadena.
sentence = '''%I $am@% a %tea@cher%, &and& I lo%#ve %tea@ching%;. There $is nothing; &as& mo@re rewarding as educa@ting &and& @emp%o@wering peo@ple. ;I found tea@ching m%o@re interesting tha@n any other %jo@bs. %Do@es thi%s mo@tivate yo@u to be a tea@cher!?'''
# Limpiamos el texto
clean_sentence = re.sub(r'[^a-zA-Z\s]', '', sentence)
# Convertimos el texto a minúsculas
clean_sentence = clean_sentence.lower()
# Separamos el texto en palabras
words = clean_sentence.split()
# Creamos un diccionario para contar la frecuencia de cada palabra
word_freq = {}
for word in words:
if word in word_freq:
word_freq[word] += 1
else:
word_freq[word] = 1
# Encontramos las tres palabras más frecuentes
most_freq_words = sorted(word_freq, key=word_freq.get, reverse=True)[:3]
print("Las tres palabras más frecuentes son:", most_freq_words)
# Ejercicios: Nivel 4
# 1. Extrae el DNI de la siguiente cadena.
dni = """Asunto: Datos para la nómina.
Respondiendo a su mail, le paso el dato personal que le faltaba. Mi DNI es 12345678A.
Saludos.
"""
# Extraemos el DNI
dni = re.search(r'\d{8}[A-Z]', dni).group()
print("DNI:", dni)

View File

@@ -0,0 +1,86 @@
# Expresiones regulares
Documento original en inglés: [Regular Expressions](https://github.com/Asabeneh/30-Days-Of-Python/blob/master/18_Day_Regular_expressions/18_regular_expressions.md)
## Ejercicios
### Ejercicios: Nivel 1
1. ¿Cuál es la palabra más frecuente en el siguiente párrafo?
```
paragraph = 'I love teaching. If you do not love teaching what else can you love. I love Python if you do not love something which can give you all the capabilities to develop an application what else can you love.
```
```
[
(6, 'love'),
(5, 'you'),
(3, 'can'),
(2, 'what'),
(2, 'teaching'),
(2, 'not'),
(2, 'else'),
(2, 'do'),
(2, 'I'),
(1, 'which'),
(1, 'to'),
(1, 'the'),
(1, 'something'),
(1, 'if'),
(1, 'give'),
(1, 'develop'),
(1, 'capabilities'),
(1, 'application'),
(1, 'an'),
(1, 'all'),
(1, 'Python'),
(1, 'If')
]
```
2. La posición de algunas partículas en el eje x horizontal son -12, -4, -3 y -1 en la dirección negativa, 0 en el origen, 4 y 8 en la dirección positiva. Extrae estos números de todo el texto y encuentra la distancia entre las dos partículas más lejanas.
```
puntos = ['-12', '-4', '-3', '-1', '0', '4', '8']
puntos_ordenados = [-12, -4, -3, -1, -1, 0, 2, 4, 8]
distancia = 8 - (-12) # La distancia es 20
```
### Ejercicios: Nivel 2
1. Escribe un patrón que identifique si una cadena es una variable válida en Python.
```
es_variable_valida('primer_nombre') # Verdadero
es_variable_valida('primer-nombre') # Falso
es_variable_valida('1primer_nombre') # Falso
es_variable_valida('nombre') # Verdadero
```
### Ejercicios: Nivel 3
1. Limpia el siguiente texto. Después de limpiarlo, cuenta las tres palabras más frecuentes en la cadena.
```
sentence = '''%I $am@% a %tea@cher%, &and& I lo%#ve %tea@ching%;. There $is nothing; &as& mo@re rewarding as educa@ting &and& @emp%o@wering peo@ple. ;I found tea@ching m%o@re interesting tha@n any other %jo@bs. %Do@es thi%s mo@tivate yo@u to be a tea@cher!?'''
print(clean_text(sentence));
I am a teacher and I love teaching There is nothing as more rewarding as educating and empowering people I found teaching more interesting than any other jobs Does this motivate you to be a teacher
print(most_frequent_words(cleaned_text)) # [(3, 'I'), (2, 'teaching'), (2, 'teacher')]
```
### Ejercicios: Nivel 4
1. Extrae el DNI de la siguiente cadena.
```
dni = """Asunto: Datos para la nómina.
Respondiendo a su mail, le paso el dato personal que le faltaba. Mi DNI es 12345678A.
Saludos.
"""
```
[Solución](01_regex.py)
[<< Day 17](../17_Manejo_de_excepciones/README.md) | [Day 19 >>](../19_Manipulación_de_archivos/README.md)

View File

@@ -0,0 +1,129 @@
"""
01_files.py
"""
import json
# Ejercicio: Nivel 1
# 1. Escribe una función que cuente el número
# de líneas y palabras en un texto.
# Todos los archivos se encuentran en la carpeta [data](./data)):
def contar_lineas_palabras(archivo):
with open(archivo, 'r') as f:
lineas = f.readlines()
f.seek(0)
palabras = f.read().split()
# Contar palabras
resultado = f'tiene {len(lineas)} lineas y {len(palabras)} palabras\n'
return resultado
# a) Lee el archivo obama_speech.txt
# y cuenta el número de líneas y palabras
print(
f"El discurso de Obama {contar_lineas_palabras('data/obama_speech.txt')}")
# b) Lee el archivo michelle_obama_speech.txt
# y cuenta el número de líneas y palabras
print(
f"El discurso de Michelle {contar_lineas_palabras('data/michelle_obama_speech.txt')}")
# c) Lee el archivo donald_speech.txt
# y cuenta el número de líneas y palabras
print(
f"El discurso de Donald {contar_lineas_palabras('data/donald_speech.txt')}")
# d) Lee el archivo melina_trump_speech.txt
# y cuenta el número de líneas y palabras
print(
f"El discurso de Melina {contar_lineas_palabras('data/melina_trump_speech.txt')}")
# 2. Lee el archivo de datos countries_data.json
# en el directorio data,
# crea una función que encuentre
# los diez idiomas más hablados.
def diez_idiomas_mas_hablados():
archivo = 'data/countries_data.json'
with open(archivo, 'r') as f:
data = json.load(f)
idiomas = []
for pais in data:
idiomas.extend(pais['languages'])
# Contamos la frecuencia de cada idioma
idiomas_freq = {}
for idioma in idiomas:
if idioma in idiomas_freq:
idiomas_freq[idioma] += 1
else:
idiomas_freq[idioma] = 1
# Ordenamos los idiomas por frecuencia
# y tomamos los 10 más comunes
diez_idiomas = sorted(
idiomas_freq.items(),
key=lambda x: x[1],
reverse=True
)[:10]
# Creamos una lista de tuplas
# que contengan el nombre del idioma
# y el número de países en los que se habla
resultado = []
for idioma, frecuencia in diez_idiomas:
resultado.append((idioma, frecuencia))
return resultado
for idioma, frecuencia in diez_idiomas_mas_hablados():
print(f"{idioma} se habla en {frecuencia} paises")
print()
# 3. Lee el archivo de datos countries_data.json
# en el directorio data,
# crea una función que genere
# una lista de los diez países más poblados.
def diez_paises_mas_poblados():
archivo = 'data/countries_data.json'
with open(archivo, 'r') as f:
data = json.load(f)
paises = []
for pais in data:
paises.append((pais['name'], pais['population']))
# Ordenamos los paises por población
# y tomamos los 10 más poblados
diez_paises = sorted(
paises,
key=lambda x: x[1],
reverse=True
)[:10]
resultado = []
for pais, poblacion in diez_paises:
poblacion_millones = poblacion / 1000000
resultado.append((pais, poblacion_millones))
return resultado
for pais, poblacion in diez_paises_mas_poblados():
print(f"{pais} tiene {poblacion:.2f} millones de habitantes")
print()

View File

@@ -0,0 +1,225 @@
"""
01_files.py
"""
import nltk
import re
from data.stop_words import stop_words
# Ejercicios: Nivel 2
# 1. Extrae todas las direcciones
# de correo electrónico entrantes
# como una lista del archivo
# email_exchange_big.txt.
def extraer_correos():
archivo = 'data/email_exchanges_big.txt'
with open(archivo, 'r') as f:
lineas = f.readlines()
correos = {}
for linea in lineas:
if linea.startswith('From '):
correo = linea.split()[1]
if correo in correos:
correos[correo] += 1
else:
correos[correo] = 1
return correos
for correo, frecuencia in extraer_correos().items():
print(f"{correo} envió {frecuencia} correos")
print()
# 2. Encuentra las palabras más comunes
# en el idioma inglés.
# Llama a tu función encontrar_palabras_mas_comunes,
# tomará dos parámetros:
# una cadena o un archivo
# y un número entero positivo
# que indicará la cantidad de palabras.
# Tu función devolverá una lista de tuplas
# en orden descendente.
def encontrar_palabras_mas_comunes(archivo, n):
with open(archivo, 'r') as f:
palabras = f.read().split()
# Etiquetamos cada palabra con su POS
palabras_pos = nltk.pos_tag(palabras)
# Filtramos las palabras que sean sustantivos o verbos
palabras_filtradas = []
for palabra, pos in palabras_pos:
if pos.startswith('N') or pos.startswith('V'):
palabras_filtradas.append(palabra)
# Contamos las palabras filtradas
palabras_freq = {}
for palabra in palabras_filtradas:
if palabra in palabras_freq:
palabras_freq[palabra] += 1
else:
palabras_freq[palabra] = 1
# Ordenamos las palabras por frecuencia
# y tomamos las n más comunes
n_palabras = sorted(
palabras_freq.items(),
key=lambda x: x[1],
reverse=True
)[:n]
# Creamos una lista de tuplas
# que contengan el nombre de la palabra
# y el número de veces que aparece
resultado = []
for palabra, frecuencia in n_palabras:
resultado.append((palabra, frecuencia))
return resultado
for palabra, frecuencia in encontrar_palabras_mas_comunes('data/romeo_and_juliet.txt', 10):
print(f"\"{palabra}\" aparece {frecuencia} veces")
print()
# 3. Utiliza la función encontrar_palabras_mas_comunes para encontrar:
# a) Las diez palabras más frecuentes utilizadas en el discurso de Obama
print('Las diez palabras más frecuentes utilizadas en el discurso de Obama')
for palabra, frecuencia in encontrar_palabras_mas_comunes('data/obama_speech.txt', 10):
print(f"\"{palabra}\" aparece {frecuencia} veces")
print()
# b) Las diez palabras más frecuentes utilizadas en el discurso de Michelle
print('Las diez palabras más frecuentes utilizadas en el discurso de Michelle')
for palabra, frecuencia in encontrar_palabras_mas_comunes('data/michelle_obama_speech.txt', 10):
print(f"\"{palabra}\" aparece {frecuencia} veces")
print()
# d) Las diez palabras más frecuentes utilizadas en el discurso de Melina
print('Las diez palabras más frecuentes utilizadas en el discurso de Melina')
for palabra, frecuencia in encontrar_palabras_mas_comunes('data/melina_trump_speech.txt', 10):
print(f"\"{palabra}\" aparece {frecuencia} veces")
print()
# c) Las diez palabras más frecuentes utilizadas en el discurso de Trump
print('Las diez palabras más frecuentes utilizadas en el discurso de Trump')
for palabra, frecuencia in encontrar_palabras_mas_comunes('data/donald_speech.txt', 10):
print(f"\"{palabra}\" aparece {frecuencia} veces")
print()
# 4. Escribe una aplicación Python
# que verifique la similitud entre dos textos.
# Toma un archivo o una cadena como parámetro
# y evaluará la similitud entre los dos textos.
# Es posible que necesites un par de funciones:
# una para limpiar el texto (limpiar_texto),
# una para eliminar las palabras de soporte
# (eliminar_palabras_soporte)
# y finalmente para verificar la similitud
# (verificar_similitud_texto).
# La lista de palabras de paro
# se encuentra en el directorio data.
def limpiar_texto(texto):
# Convertir todo a minúsculas
texto = texto.lower()
# Eliminar caracteres no alfabéticos
texto = re.sub(r'[^a-záéíóúñ]', ' ', texto)
# Eliminar espacios en blanco adicionales
texto = re.sub(r'\s+', ' ', texto)
return texto.strip()
def eliminar_palabras_soporte(texto, palabras_soporte):
palabras = texto.split()
palabras_filtradas = [
palabra for palabra in palabras if palabra not in palabras_soporte]
return ' '.join(palabras_filtradas)
def verificar_similitud_texto(texto1, texto2, palabras_soporte):
texto1 = limpiar_texto(texto1)
texto2 = limpiar_texto(texto2)
texto1 = eliminar_palabras_soporte(texto1, palabras_soporte)
texto2 = eliminar_palabras_soporte(texto2, palabras_soporte)
palabras1 = set(texto1.split())
palabras2 = set(texto2.split())
similitud = len(palabras1 & palabras2) / len(palabras1 | palabras2)
return similitud
# Leer los archivos de texto
with open('./data/michelle_obama_speech.txt', 'r') as f:
texto1 = f.read()
with open('./data/melina_trump_speech.txt', 'r') as f:
texto2 = f.read()
# Calcular la similitud entre los textos
similitud = verificar_similitud_texto(texto1, texto2, stop_words)
# Mostrar el resultado como un porcentaje
porcentaje_similitud = similitud * 100
print(f"La similitud entre los textos es de un {porcentaje_similitud:.2f}%\n")
# 5. Encuentra las 10 palabras más repetidas en romeo_and_juliet.txt.
for palabra, frecuencia in encontrar_palabras_mas_comunes('data/romeo_and_juliet.txt', 10):
print(f"\"{palabra}\" aparece {frecuencia} veces")
print()
# 6. Lee el archivo CSV de hacker news y averigua:
def contar_lineas(palabra):
archivo = 'data/hacker_news.csv'
with open(archivo, 'r') as f:
lineas = f.readlines()
contador = 0
for linea in lineas:
if palabra in linea:
contador += 1
return contador
# a) Cuántas líneas contienen python o Python
contador_python = contar_lineas('python') + contar_lineas('Python')
print(
f"El archivo contiene {contador_python} líneas que contienen 'python' o 'Python'.")
# b) Cuántas líneas contienen JavaScript, javascript o Javascript
contador_javascript = contar_lineas(
'JavaScript') + contar_lineas('javascript') + contar_lineas('Javascript')
print(
f"El archivo contiene {contador_javascript} líneas que contienen 'JavaScript', 'javascript' o 'Javascript'.")
# c) Cuántas líneas contienen Java y no JavaScript
contador_java = contar_lineas('Java')
contador_javascript = contar_lineas(
'JavaScript') + contar_lineas('Javascript')
contador_java_sin_javascript = contador_java - contador_javascript
print(
f"El archivo contiene {contador_java_sin_javascript} líneas que contienen 'Java' pero no 'JavaScript', 'javascript' o 'Javascript'.")

View File

@@ -0,0 +1,118 @@
# Manipulación de archivos
Documento original en inglés: [file handling](https://github.com/Asabeneh/30-Days-Of-Python/blob/master/19_Day_File_handling/19_file_handling.md)
## Ejercicios
### Ejercicios: Nivel 1
1. Escribe una función que cuente el número de líneas y palabras en un texto. Todos los archivos se encuentran en la carpeta [data](./data):
a) Lee el archivo obama_speech.txt y cuenta el número de líneas y palabras
b) Lee el archivo michelle_obama_speech.txt y cuenta el número de líneas y palabras
c) Lee el archivo donald_speech.txt y cuenta el número de líneas y palabras
d) Lee el archivo melina_trump_speech.txt y cuenta el número de líneas y palabras
2. Lee el archivo de datos countries_data.json en el directorio data, crea una función que encuentre los diez idiomas más hablados.
```py
# Tu resultado debería lucir de la siguiente manera
print(idiomas_mas_hablados(archivo='./data/countries_data.json', top=10))
[
{'idioma': 'Inglés', 'cantidad': 91},
{'idioma': 'Francés', 'cantidad': 45},
{'idioma': 'Árabe', 'cantidad': 25},
{'idioma': 'Español', 'cantidad': 24},
{'idioma': 'Ruso', 'cantidad': 9},
{'idioma': 'Portugués', 'cantidad': 9},
{'idioma': 'Holandés', 'cantidad': 8},
{'idioma': 'Alemán', 'cantidad': 7},
{'idioma': 'Chino', 'cantidad': 5},
{'idioma': 'Suajili', 'cantidad': 4}
]
# Tu resultado debería lucir de la siguiente manera
print(idiomas_mas_hablados(archivo='./data/countries_data.json', top=3))
[
{'idioma': 'Inglés', 'cantidad': 91},
{'idioma': 'Francés', 'cantidad': 45},
{'idioma': 'Árabe', 'cantidad': 25}
]
```
3. Lee el archivo de datos countries_data.json en el directorio data, crea una función que genere una lista de los diez países más poblados.
```py
# Tu resultado debería lucir de la siguiente manera
print(paises_mas_poblados(archivo='./data/countries_data.json', top=10))
[
{'país': 'China', 'población': 1377422166},
{'país': 'India', 'población': 1295210000},
{'país': 'Estados Unidos de América', 'población': 323947000},
{'país': 'Indonesia', 'población': 258705000},
{'país': 'Brasil', 'población': 206135893},
{'país': 'Pakistán', 'población': 194125062},
{'país': 'Nigeria', 'población': 186988000},
{'país': 'Bangladesh', 'población': 161006790},
{'país': 'Federación Rusa', 'población': 146599183},
{'país': 'Japón', 'población': 126960000}
]
# Tu resultado debería lucir de la siguiente manera
print(paises_mas_poblados(archivo='./data/countries_data.json', top=3))
[
{'país': 'China', 'población': 1377422166},
{'país': 'India', 'población': 1295210000},
{'país': 'Estados Unidos de América', 'población': 323947000}
]
```
[Solución](01_files.py)
### Ejercicios: Nivel 2
1. Extrae todas las direcciones de correo electrónico entrantes como una lista del archivo email_exchange_big.txt.
2. Encuentra las palabras más comunes en el idioma inglés. Llama a tu función encontrar_palabras_mas_comunes, tomará dos parámetros: una cadena o un archivo y un número entero positivo que indicará la cantidad de palabras. Tu función devolverá una lista de tuplas en orden descendente. Comprueba el resultado.
```py
# Tu resultado debería lucir de la siguiente manera
print(encontrar_palabras_mas_comunes('muestra.txt', 10))
[(10, 'the'),
(8, 'be'),
(6, 'to'),
(6, 'of'),
(5, 'and'),
(4, 'a'),
(4, 'in'),
(3, 'that'),
(2, 'have'),
(2, 'I')]
# Tu resultado debería lucir de la siguiente manera
print(encontrar_palabras_mas_comunes('muestra.txt', 5))
[(10, 'the'),
(8, 'be'),
(6, 'to'),
(6, 'of'),
(5, 'and')]
```
3. Utiliza la función encontrar_palabras_mas_comunes para encontrar:
a) Las diez palabras más frecuentes utilizadas en el discurso de Obama
b) Las diez palabras más frecuentes utilizadas en el discurso de Michelle
d) Las diez palabras más frecuentes utilizadas en el discurso de Melina
c) Las diez palabras más frecuentes utilizadas en el discurso de Trump
4. Escribe una aplicación Python que verifique la similitud entre dos textos. Toma un archivo o una cadena como parámetro y evaluará la similitud entre los dos textos. Es posible que necesites un par de funciones: una para limpiar el texto (limpiar_texto), una para eliminar las palabras de soporte (eliminar_palabras_soporte) y finalmente para verificar la similitud (verificar_similitud_texto). La lista de palabras de paro se encuentra en el directorio data.
5. Encuentra las 10 palabras más repetidas en romeo_and_juliet.txt.
6. Lee el archivo CSV de hacker news y averigua:
a) Cuántas líneas contienen python o Python
b) Cuántas líneas contienen JavaScript, javascript o Javascript
c) Cuántas líneas contienen Java y no JavaScript
[Solución](02_files.py)
[<< Day 18](../18_Expresiones_regulares/README.md) | [Day 20 >>](../20_Gestor_de_paquetes_de_Python/README.md)

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,48 @@
Chief Justice Roberts, President Carter, President Clinton,President Bush, fellow Americans and people of the world thank you.
We the citizens of America have now joined a great national effort to rebuild our county and restore its promise for all our people.
Together we will determine the course of America for many, many years to come.
Together we will face challenges. We will confront hardships. But we will get the job done.
Every four years we gather on these steps to carry out the orderly and peaceful transfer of power.
And we are grateful to President Obama and First Lady Michelle Obama for their gracious aid throughout this transition. They have been magnificent, thank you.
Todays ceremony, however, has very special meaning because today we are not merely transferring power from one administration to another but transferring it from Washington DC and giving it back to you the people.
For too long a small group in our nations capital has reaped the rewards of government while the people have borne the cost.
Washington flourished but the people did not share in its wealth. Politicians prospered but the jobs left and the factories closed.The establishment protected itself but not the citizens of our country.
Their victories have not been your victories. Their triumphs have not been your triumphs. While they have celebrated there has been little to celebrate for struggling families all across our land.
That all changes starting right here and right now because this moment is your moment. It belongs to you. It belongs to everyone gathered here today and everyone watching all across America today.
This is your day.This is your celebration.And this the United States of America is your country.What truly matters is not what party controls our government but that this government is controlled by the people.
Today, January 20 2017, will be remembered as the day the people became the rulers of this nation again.The forgotten men and women of our country will be forgotten no longer. Everyone is listening to you now.
You came by the tens of millions to become part of a historic movement the likes of which the world has never seen before.
At the centre of this movement is a crucial conviction that a nation exists to serve its citizens.Americans want great schools for their children, safe neighbourhoods for their families and good jobs for themselves.
These are just and reasonable demands.Mothers and children trapped in poverty in our inner cities, rusted out factories scattered like tombstones across the landscape of our nation.
An education system flushed with cash, but which leaves our young and beautiful students deprived of all knowledge. And the crime and the gangs and the drugs which deprive people of so much unrealised potential.
We are one nation, and their pain is our pain, their dreams are our dreams, we share one nation, one home and one glorious destiny.
Today I take an oath of allegiance to all Americans. For many decades, weve enriched foreign industry at the expense of American industry, subsidised the armies of other countries, while allowing the sad depletion of our own military.
We've defended other nations borders while refusing to defend our own.And spent trillions and trillions of dollars overseas while Americas infrastructure has fallen into disrepair and decay.
We have made other countries rich while the wealth, strength and confidence of our country has dissipated over the horizon.
One by one, shutters have closed on our factories without even a thought about the millions and millions of those who have been left behind.
But that is the past and now we are looking only to the future.
We assembled here today are issuing a new decree to be heard in every city, in every foreign capital, in every hall of power from this day on a new vision will govern our land from this day onwards it is only going to be America first America first!
Every decision on trade, on taxes, on immigration, on foreign affairs will be made to benefit American workers and American families.
Protection will lead to great prosperity and strength. I will fight for you with every bone in my body and I will never ever let you down.
America will start winning again. America will start winning like never before.
We will bring back our jobs, we will bring back our borders, we will bring back our wealth, we will bring back our dreams.
We will bring new roads and high roads and bridges and tunnels and railways all across our wonderful nation.
We will get our people off welfare and back to work rebuilding our country with American hands and American labour.
We will follow two simple rules buy American and hire American.
We see good will with the nations of the world but we do so with the understanding that it is the right of all nations to put their nations first.
We will shine for everyone to follow.We will reinforce old alliances and form new ones, and untie the world against radical Islamic terrorism which we will eradicate from the face of the earth.
At the bed rock of our politics will be an allegiance to the United States.And we will discover new allegiance to each other. There is no room for prejudice.
The bible tells us how good and pleasant it is when gods people live together in unity.When America is united, America is totally unstoppable
There is no fear, we are protected and will always be protected by the great men and women of our military and most importantly we will be protected by god.
Finally, we must think big and dream even bigger. As Americans, we know we live as a nation only when it is striving.
We will no longer accept politicians who are always complaining but never doing anything about it.The time for empty talk is over, now arrives the hour of action.
Do not allow anyone to tell you it cannot be done. No challenge can match the heart and fight and spirit of America. We will not fail, our country will thrive and prosper again.
We stand at the birth of a new millennium, ready to unlock the mysteries of space, to free the earth from the miseries of disease, to harvest the energies, industries and technologies of tomorrow.
A new national pride will stir ourselves, lift our sights and heal our divisions. Its time to remember that old wisdom our soldiers will never forget, that whether we are black or brown or white, we all bleed the same red blood of patriots.
We all enjoy the same glorious freedoms and we all salute the same great American flag and whether a child is born in the urban sprawl of Detroit or the windswept plains of Nebraska, they look at the same night sky, and dream the same dreams, and they are infused with the breath by the same almighty creator.
So to all Americans in every city near and far, small and large, from mountain to mountain, from ocean to ocean hear these words you will never be ignored again.
Your voice, your hopes and dreams will define your American destiny.Your courage, goodness and love will forever guide us along the way.
Together we will make America strong again, we will make America wealthy again, we will make America safe again and yes together we will make America great again.
Thank you.
God bless you.
And god bless America.

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,33 @@
Thank you very much. Thank you. You have all been very kind to Donald and me, to our young son Barron, and to our whole family. It's a very nice welcome and we're excited to be with you at this historic convention. I am so proud of your choice for president of the United States, my husband, Donald J. Trump.
And I can assure you, he is moved by this great honor. The 2016 Republican primaries were fierce and started with many candidates, 17 to be exact, and I know that Donald agrees with me when I mention how talented all of them are. They deserve respect and gratitude from all of us.
However, when it comes to my husband, I will say that I am definitely biased, and for good reason.
I have been with Donald for 18 years and I have been aware of his love for this country since we first met. He never had a hidden agenda when it comes to his patriotism, because, like me, he loves this country so much. I was born in Slovenia, a small, beautiful and then-communist country in Central Europe. My sister Ines, who is an incredible woman and a friend, and I were raised by my wonderful parents. My elegant and hard-working mother Amalia introduced me to fashion and beauty. My father Viktor instilled in me a passion for business and travel. Their integrity, compassion and intelligence reflects to this day on me and for my love of family and America.
From a young age, my parents impressed on me the values that you work hard for what you want in life; that your word is your bond and you do what you say and keep your promise; that you treat people with respect. They taught and showed me values and morals in their daily life. That is a lesson that I continue to pass along to our son, and we need to pass those lessons on to the many generations to follow. Because we want our children in this nation to know that the only limit to your achievements is the strength of your dreams and your willingness to work for them.
I am fortunate for my heritage, but also for where it brought me today. I traveled the world while working hard in the incredible arena of fashion. After living and working in Milan and Paris, I arrived in New York City 20 years ago, and I saw both the joys and the hardships of daily life. On July 28, 2006, I was very proud to become a citizen of the United States — the greatest privilege on planet Earth. I cannot, or will not, take the freedoms this country offers for granted. But these freedoms have come with a price so many times. The sacrifices made by our veterans are reminders to us of this. I would like to take this moment to recognize an amazing veteran, the great Sen. Bob Dole. And let us thank all of our veterans in the arena today, and those across our great country. We are all truly blessed to be here. That will never change.
I can tell you with certainty that my husband has been concerned about our country for as long as I have known him. With all of my heart, I know that he will make a great and lasting difference. Donald has a deep and unbounding determination and a never-give-up attitude. I have seen him fight for years to get a project done — or even started — and he does not give up! If you want someone to fight for you and your country, I can assure you, he is the "guy."
He will never, ever, give up. And, most importantly, he will never, ever, let you down. Donald is, and always has been, an amazing leader. Now, he will go to work for you. His achievements speak for themselves, and his performance throughout the primary campaign proved that he knows how to win. He also knows how to remain focused on improving our country — on keeping it safe and secure. He is tough when he has to be but he is also kind and fair and caring. This kindness is not always noted, but it is there for all to see. That is one reason I fell in love with him to begin with.
Donald is intensely loyal. To family, friends, employees, country. He has the utmost respect for his parents, Mary and Fred, to his sisters Maryanne and Elizabeth, to his brother Robert and to the memory of his late brother Fred. His children have been cared for and mentored to the extent that even his adversaries admit they are an amazing testament to who he is as a man and a father. There is a great deal of love in the Trump family. That is our bond, and that is our strength.
Yes, Donald thinks big, which is especially important when considering the presidency of the United States. No room for small thinking. No room for small results. Donald gets things done.
Our country is underperforming and needs new leadership. Leadership is also what the world needs. Donald wants our country to move forward in the most positive of ways. Everyone wants change. Donald is the only one that can deliver it. We should not be satisfied with stagnation. Donald wants prosperity for all Americans. We need new programs to help the poor and opportunities to challenge the young. There has to be a plan for growth — only then will fairness result.
My husband's experience exemplifies growth and successful passage of opportunity to the next generation. His success indicates inclusion rather than division. My husband offers a new direction, welcoming change, prosperity and greater cooperation among peoples and nations. Donald intends to represent all the people, not just some of the people. That includes Christians and Jews and Muslims, it includes Hispanics and African Americans and Asians, and the poor and the middle-class. Throughout his career, Donald has successfully worked with people of many faiths and with many nations.
Like no one else, I have seen the talent, the energy, the tenacity, the resourceful mind, and the simple goodness of heart that God gave to Donald Trump. Now is the time to use those gifts as never before, for purposes far greater than ever before. And he will do this better than anyone else can — and it won't even be close. Everything depends on it, for our cause and for our country.
People are counting on him — all the millions of you who have touched us so much with your kindness and your confidence. You have turned this unlikely campaign into a movement that is still gaining in strength and number. The primary season, and its toughness, is behind us. Let's all come together in a national campaign like no other.
The race will be hard-fought, all the way to November. There will be good times and hard times and unexpected turns — it would not be a Trump contest without excitement and drama. But through it all, my husband will remain focused on only one thing: this beautiful country, that he loves so much.
If I am honored to serve as first lady, I will use that wonderful privilege to try to help people in our country who need it the most. One of the many causes dear to my heart is helping children and women. You judge a society by how it treats its citizens. We must do our best to ensure that every child can live in comfort and security, with the best possible education. As citizens of this great nation, it is kindness, love, and compassion for each other that will bring us together — and keep us together. These are the values Donald and I will bring to the White House. My husband is ready to lead this great nation. He is ready to fight, every day, to give our children the better future they deserve. Ladies and gentlemen, Donald J. Trump is ready to serve and lead this country as the next president of the United States.
Thank you, God bless you, and God bless America.

View File

@@ -0,0 +1,83 @@
As you might imagine, for Barack, running for president is nothing compared to that first game of basketball with my brother, Craig.
I can't tell you how much it means to have Craig and my mom here tonight. Like Craig, I can feel my dad looking down on us, just as I've felt his presence in every grace-filled moment of my life.
At 6-foot-6, I've often felt like Craig was looking down on me too ... literally. But the truth is, both when we were kids and today, he wasn't looking down on me. He was watching over me.
And he's been there for me every step of the way since that clear February day 19 months ago, when — with little more than our faith in each other and a hunger for change — we joined my husband, Barack Obama, on the improbable journey that's brought us to this moment.
But each of us also comes here tonight by way of our own improbable journey.
I come here tonight as a sister, blessed with a brother who is my mentor, my protector and my lifelong friend.
I come here as a wife who loves my husband and believes he will be an extraordinary president.
I come here as a mom whose girls are the heart of my heart and the center of my world — they're the first thing I think about when I wake up in the morning, and the last thing I think about when I go to bed at night. Their future — and all our children's future — is my stake in this election.
And I come here as a daughter — raised on the South Side of Chicago by a father who was a blue-collar city worker and a mother who stayed at home with my brother and me. My mother's love has always been a sustaining force for our family, and one of my greatest joys is seeing her integrity, her compassion and her intelligence reflected in my own daughters.
My dad was our rock. Although he was diagnosed with multiple sclerosis in his early 30s, he was our provider, our champion, our hero. As he got sicker, it got harder for him to walk, it took him longer to get dressed in the morning. But if he was in pain, he never let on. He never stopped smiling and laughing — even while struggling to button his shirt, even while using two canes to get himself across the room to give my mom a kiss. He just woke up a little earlier and worked a little harder.
He and my mom poured everything they had into me and Craig. It was the greatest gift a child can receive: never doubting for a single minute that you're loved, and cherished, and have a place in this world. And thanks to their faith and hard work, we both were able to go on to college. So I know firsthand from their lives — and mine — that the American dream endures.
And you know, what struck me when I first met Barack was that even though he had this funny name, even though he'd grown up all the way across the continent in Hawaii, his family was so much like mine. He was raised by grandparents who were working-class folks just like my parents, and by a single mother who struggled to pay the bills just like we did. Like my family, they scrimped and saved so that he could have opportunities they never had themselves. And Barack and I were raised with so many of the same values: that you work hard for what you want in life; that your word is your bond and you do what you say you're going to do; that you treat people with dignity and respect, even if you don't know them, and even if you don't agree with them.
And Barack and I set out to build lives guided by these values, and pass them on to the next generation. Because we want our children — and all children in this nation — to know that the only limit to the height of your achievements is the reach of your dreams and your willingness to work for them.
And as our friendship grew, and I learned more about Barack, he introduced me to the work he'd done when he first moved to Chicago after college. Instead of heading to Wall Street, Barack had gone to work in neighborhoods devastated when steel plants shut down and jobs dried up. And he'd been invited back to speak to people from those neighborhoods about how to rebuild their community.
The people gathered together that day were ordinary folks doing the best they could to build a good life. They were parents living paycheck to paycheck; grandparents trying to get by on a fixed income; men frustrated that they couldn't support their families after their jobs disappeared. Those folks weren't asking for a handout or a shortcut. They were ready to work — they wanted to contribute. They believed — like you and I believe — that America should be a place where you can make it if you try.
Barack stood up that day, and spoke words that have stayed with me ever since. He talked about "The world as it is" and "The world as it should be." And he said that all too often, we accept the distance between the two, and settle for the world as it is — even when it doesn't reflect our values and aspirations. But he reminded us that we know what our world should look like. We know what fairness and justice and opportunity look like. And he urged us to believe in ourselves — to find the strength within ourselves to strive for the world as it should be. And isn't that the great American story?
It's the story of men and women gathered in churches and union halls, in town squares and high school gyms — people who stood up and marched and risked everything they had — refusing to settle, determined to mold our future into the shape of our ideals.
It is because of their will and determination that this week, we celebrate two anniversaries: the 88th anniversary of women winning the right to vote, and the 45th anniversary of that hot summer day when [Dr. Martin Luther King Jr.] lifted our sights and our hearts with his dream for our nation.
I stand here today at the crosscurrents of that history — knowing that my piece of the American dream is a blessing hard won by those who came before me. All of them driven by the same conviction that drove my dad to get up an hour early each day to painstakingly dress himself for work. The same conviction that drives the men and women I've met all across this country:
People who work the day shift, kiss their kids goodnight, and head out for the night shift — without disappointment, without regret — that goodnight kiss a reminder of everything they're working for.
The military families who say grace each night with an empty seat at the table. The servicemen and women who love this country so much, they leave those they love most to defend it.
The young people across America serving our communities — teaching children, cleaning up neighborhoods, caring for the least among us each and every day.
People like Hillary Clinton, who put those 18 million cracks in the glass ceiling, so that our daughters — and sons — can dream a little bigger and aim a little higher.
People like Joe Biden, who's never forgotten where he came from and never stopped fighting for folks who work long hours and face long odds and need someone on their side again.
All of us driven by a simple belief that the world as it is just won't do — that we have an obligation to fight for the world as it should be.
That is the thread that connects our hearts. That is the thread that runs through my journey and Barack's journey and so many other improbable journeys that have brought us here tonight, where the current of history meets this new tide of hope.
That is why I love this country.
And in my own life, in my own small way, I've tried to give back to this country that has given me so much. That's why I left a job at a law firm for a career in public service, working to empower young people to volunteer in their communities. Because I believe that each of us — no matter what our age or background or walk of life — each of us has something to contribute to the life of this nation.
It's a belief Barack shares — a belief at the heart of his life's work.
It's what he did all those years ago, on the streets of Chicago, setting up job training to get people back to work and after-school programs to keep kids safe — working block by block to help people lift up their families.
It's what he did in the Illinois Senate, moving people from welfare to jobs, passing tax cuts for hard-working families, and making sure women get equal pay for equal work.
It's what he's done in the United States Senate, fighting to ensure the men and women who serve this country are welcomed home not just with medals and parades but with good jobs and benefits and health care — including mental health care.
That's why he's running — to end the war in Iraq responsibly, to build an economy that lifts every family, to make health care available for every American, and to make sure every child in this nation gets a world class education all the way from preschool to college. That's what Barack Obama will do as president of the United States of America.
He'll achieve these goals the same way he always has — by bringing us together and reminding us how much we share and how alike we really are. You see, Barack doesn't care where you're from, or what your background is, or what party — if any — you belong to. That's not how he sees the world. He knows that thread that connects us — our belief in America's promise, our commitment to our children's future — is strong enough to hold us together as one nation even when we disagree.
It was strong enough to bring hope to those neighborhoods in Chicago.
It was strong enough to bring hope to the mother he met worried about her child in Iraq; hope to the man who's unemployed, but can't afford gas to find a job; hope to the student working nights to pay for her sister's health care, sleeping just a few hours a day.
And it was strong enough to bring hope to people who came out on a cold Iowa night and became the first voices in this chorus for change that's been echoed by millions of Americans from every corner of this nation.
Millions of Americans who know that Barack understands their dreams; that Barack will fight for people like them; and that Barack will finally bring the change we need.
And in the end, after all that's happened these past 19 months, the Barack Obama I know today is the same man I fell in love with 19 years ago. He's the same man who drove me and our new baby daughter home from the hospital 10 years ago this summer, inching along at a snail's pace, peering anxiously at us in the rearview mirror, feeling the whole weight of her future in his hands, determined to give her everything he'd struggled so hard for himself, determined to give her what he never had: the affirming embrace of a father's love.
And as I tuck that little girl and her little sister into bed at night, I think about how one day, they'll have families of their own. And one day, they — and your sons and daughters — will tell their own children about what we did together in this election. They'll tell them how this time, we listened to our hopes, instead of our fears. How this time, we decided to stop doubting and to start dreaming. How this time, in this great country — where a girl from the South Side of Chicago can go to college and law school, and the son of a single mother from Hawaii can go all the way to the White House we committed ourselves to building the world as it should be.
So tonight, in honor of my father's memory and my daughters' future — out of gratitude to those whose triumphs we mark this week, and those whose everyday sacrifices have brought us to this moment — let us devote ourselves to finishing their work; let us work together to fulfill their hopes; and let us stand together to elect Barack Obama president of the United States of America.
Thank you, God bless you, and God bless America.

View File

@@ -0,0 +1,66 @@
My fellow citizens:I stand here today humbled by the task before us, grateful for the trust you have bestowed, mindful of the sacrifices borne by our ancestors. I thank President Bush for his service to our nation, as well as the generosity and cooperation he has shown throughout this transition.
Forty-four Americans have now taken the presidential oath. The words have been spoken during rising tides of prosperity and the still waters of peace. Yet, every so often the oath is taken amidst gathering clouds and raging storms. At these moments, America has carried on not simply because of the skill or vision of those in high office, but because We the People have remained faithful to the ideals of our forbearers, and true to our founding documents.
So it has been. So it must be with this generation of Americans.
That we are in the midst of crisis is now well understood. Our nation is at war, against a far-reaching network of violence and hatred. Our economy is badly weakened, a consequence of greed and irresponsibility on the part of some, but also our collective failure to make hard choices and prepare the nation for a new age. Homes have been lost; jobs shed; businesses shuttered. Our health care is too costly; our schools fail too many; and each day brings further evidence that the ways we use energy strengthen our adversaries and threaten our planet.
These are the indicators of crisis, subject to data and statistics. Less measurable but no less profound is a sapping of confidence across our land - a nagging fear that America's decline is inevitable, and that the next generation must lower its sights.
Today I say to you that the challenges we face are real. They are serious and they are many.
They will not be met easily or in a short span of time. But know this, America - they will be met. On this day, we gather because we have chosen hope over fear, unity of purpose over conflict and discord.
On this day, we come to proclaim an end to the petty grievances and false promises, the recriminations and worn out dogmas, that for far too long have strangled our politics.
We remain a young nation, but in the words of Scripture, the time has come to set aside childish things. The time has come to reaffirm our enduring spirit; to choose our better history; to carry forward that precious gift, that noble idea, passed on from generation to generation: the God-given promise that all are equal, all are free, and all deserve a chance to pursue their full measure of happiness.
In reaffirming the greatness of our nation, we understand that greatness is never a given. It must be earned. Our journey has never been one of short-cuts or settling for less. It has not been the path for the faint-hearted - for those who prefer leisure over work, or seek only the pleasures of riches and fame. Rather, it has been the risk-takers, the doers, the makers of things - some celebrated but more often men and women obscure in their labor, who have carried us up the long, rugged path towards prosperity and freedom.
For us, they packed up their few worldly possessions and traveled across oceans in search of a new life.
For us, they toiled in sweatshops and settled the West; endured the lash of the whip and plowed the hard earth.
For us, they fought and died, in places like Concord and Gettysburg; Normandy and Khe Sahn. Time and again these men and women struggled and sacrificed and worked till their hands were raw so that we might live a better life. They saw America as bigger than the sum of our individual ambitions; greater than all the differences of birth or wealth or faction.
This is the journey we continue today. We remain the most prosperous, powerful nation on Earth. Our workers are no less productive than when this crisis began. Our minds are no less inventive, our goods and services no less needed than they were last week or last month or last year. Our capacity remains undiminished. But our time of standing pat, of protecting narrow interests and putting off unpleasant decisions - that time has surely passed. Starting today, we must pick ourselves up, dust ourselves off, and begin again the work of remaking America.
For everywhere we look, there is work to be done. The state of the economy calls for action, bold and swift, and we will act - not only to create new jobs, but to lay a new foundation for growth. We will build the roads and bridges, the electric grids and digital lines that feed our commerce and bind us together. We will restore science to its rightful place, and wield technology's wonders to raise health care's quality and lower its cost. We will harness the sun and the winds and the soil to fuel our cars and run our factories. And we will transform our schools and colleges and universities to meet the demands of a new age. All this we can do. And all this we will do.
Now, there are some who question the scale of our ambitions - who suggest that our system cannot tolerate too many big plans. Their memories are short. For they have forgotten what this country has already done; what free men and women can achieve when imagination is joined to common purpose, and necessity to courage.
What the cynics fail to understand is that the ground has shifted beneath them - that the stale political arguments that have consumed us for so long no longer apply. The question we ask today is not whether our government is too big or too small, but whether it works - whether it helps families find jobs at a decent wage, care they can afford, a retirement that is dignified. Where the answer is yes, we intend to move forward. Where the answer is no, programs will end. And those of us who manage the public's dollars will be held to account - to spend wisely, reform bad habits, and do our business in the light of day - because only then can we restore the vital trust between a people and their government.
Nor is the question before us whether the market is a force for good or ill. Its power to generate wealth and expand freedom is unmatched, but this crisis has reminded us that without a watchful eye, the market can spin out of control - and that a nation cannot prosper long when it favors only the prosperous. The success of our economy has always depended not just on the size of our Gross Domestic Product, but on the reach of our prosperity; on our ability to extend opportunity to every willing heart - not out of charity, but because it is the surest route to our common good.
As for our common defense, we reject as false the choice between our safety and our ideals. Our Founding Fathers, faced with perils we can scarcely imagine, drafted a charter to assure the rule of law and the rights of man, a charter expanded by the blood of generations. Those ideals still light the world, and we will not give them up for expedience's sake. And so to all other peoples and governments who are watching today, from the grandest capitals to the small village where my father was born: know that America is a friend of each nation and every man, woman, and child who seeks a future of peace and dignity, and that we are ready to lead once more.
Recall that earlier generations faced down fascism and communism not just with missiles and tanks, but with sturdy alliances and enduring convictions. They understood that our power alone cannot protect us, nor does it entitle us to do as we please. Instead, they knew that our power grows through its prudent use; our security emanates from the justness of our cause, the force of our example, the tempering qualities of humility and restraint.
We are the keepers of this legacy. Guided by these principles once more, we can meet those new threats that demand even greater effort - even greater cooperation and understanding between nations. We will begin to responsibly leave Iraq to its people, and forge a hard-earned peace in Afghanistan. With old friends and former foes, we will work tirelessly to lessen the nuclear threat, and roll back the specter of a warming planet. We will not apologize for our way of life, nor will we waver in its defense, and for those who seek to advance their aims by inducing terror and slaughtering innocents, we say to you now that our spirit is stronger and cannot be broken; you cannot outlast us, and we will defeat you.
For we know that our patchwork heritage is a strength, not a weakness. We are a nation of Christians and Muslims, Jews and Hindus - and non-believers. We are shaped by every language and culture, drawn from every end of this Earth; and because we have tasted the bitter swill of civil war and segregation, and emerged from that dark chapter stronger and more united, we cannot help but believe that the old hatreds shall someday pass; that the lines of tribe shall soon dissolve; that as the world grows smaller, our common humanity shall reveal itself; and that America must play its role in ushering in a new era of peace.
To the Muslim world, we seek a new way forward, based on mutual interest and mutual respect.
To those leaders around the globe who seek to sow conflict, or blame their society's ills on the West - know that your people will judge you on what you can build, not what you destroy. To those who cling to power through corruption and deceit and the silencing of dissent, know that you are on the wrong side of history; but that we will extend a hand if you are willing to unclench your fist.
To the people of poor nations, we pledge to work alongside you to make your farms flourish and let clean waters flow; to nourish starved bodies and feed hungry minds. And to those nations like ours that enjoy relative plenty, we say we can no longer afford indifference to suffering outside our borders; nor can we consume the world's resources without regard to effect. For the world has changed, and we must change with it.
As we consider the road that unfolds before us, we remember with humble gratitude those brave Americans who, at this very hour, patrol far-off deserts and distant mountains. They have something to tell us today, just as the fallen heroes who lie in Arlington whisper through the ages.
We honor them not only because they are guardians of our liberty, but because they embody the spirit of service; a willingness to find meaning in something greater than themselves. And yet, at this moment - a moment that will define a generation - it is precisely this spirit that must inhabit us all.
For as much as government can do and must do, it is ultimately the faith and determination of the American people upon which this nation relies. It is the kindness to take in a stranger when the levees break, the selflessness of workers who would rather cut their hours than see a friend lose their job which sees us through our darkest hours. It is the firefighter's courage to storm a stairway filled with smoke, but also a parent's willingness to nurture a child, that finally decides our fate.
Our challenges may be new. The instruments with which we meet them may be new. But those values upon which our success depends - hard work and honesty, courage and fair play, tolerance and curiosity, loyalty and patriotism - these things are old. These things are true. They have been the quiet force of progress throughout our history. What is demanded then is a return to these truths. What is required of us now is a new era of responsibility - a recognition, on the part of every American, that we have duties to ourselves, our nation, and the world, duties that we do not grudgingly accept but rather seize gladly, firm in the knowledge that there is nothing so satisfying to the spirit, so defining of our character, than giving our all to a difficult task.
This is the price and the promise of citizenship.
This is the source of our confidence - the knowledge that God calls on us to shape an uncertain destiny.
This is the meaning of our liberty and our creed - why men and women and children of every race and every faith can join in celebration across this magnificent mall, and why a man whose father less than sixty years ago might not have been served at a local restaurant can now stand before you to take a most sacred oath.
So let us mark this day with remembrance, of who we are and how far we have traveled. In the year of America's birth, in the coldest of months, a small band of patriots huddled by dying campfires on the shores of an icy river. The capital was abandoned. The enemy was advancing. The snow was stained with blood. At a moment when the outcome of our revolution was most in doubt, the father of our nation ordered these words be read to the people:
"Let it be told to the future world...that in the depth of winter, when nothing but hope and virtue could survive...that the city and the country, alarmed at one common danger, came forth to meet [it]."
America. In the face of our common dangers, in this winter of our hardship, let us remember these timeless words. With hope and virtue, let us brave once more the icy currents, and endure what storms may come. Let it be said by our children's children that when we were tested we refused to let this journey end, that we did not turn back nor did we falter; and with eyes fixed on the horizon and God's grace upon us, we carried forth that great gift of freedom and delivered it safely to future generations.

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,2 @@
stop_words = ['i','me','my', 'myself', 'we', 'our', 'ours', 'ourselves', 'you', "you're", "you've", "you'll", "you'd", 'your', 'yours', 'yourself', 'yourselves', 'he', 'him', 'his', 'himself', 'she', "she's", 'her', 'hers', 'herself', 'it', "it's", 'its', 'itself', 'they', 'them', 'their', 'theirs', 'themselves', 'what', 'which', 'who', 'whom', 'this', 'that', "that'll", 'these', 'those', 'am', 'is', 'are', 'was', 'were', 'be', 'been', 'being', 'have', 'has', 'had', 'having', 'do', 'does', 'did', 'doing', 'a', 'an', 'the', 'and', 'but', 'if', 'or', 'because', 'as', 'until', 'while', 'of', 'at', 'by', 'for', 'with', 'about', 'against', 'between', 'into', 'through', 'during', 'before', 'after', 'above', 'below', 'to', 'from', 'up','down', 'in', 'out', 'on', 'off', 'over', 'under', 'again', 'further', 'then', 'once', 'here', 'there', 'when', 'where', 'why', 'how', 'all', 'any', 'both', 'each', 'few', 'more', 'most', 'other', 'some', 'such', 'no', 'nor', 'not', 'only', 'own', 'same', 'so', 'than', 'too', 'very', 's', 't', 'can', 'will', 'just', 'don', "don't", 'should', "should've", 'now', 'd', 'll', 'm', 'o', 're', 've', 'y', 'ain', 'aren', "aren't", 'couldn', "couldn't", 'didn', "didn't", 'doesn', "doesn't", 'hadn', "hadn't", 'hasn', "hasn't", 'haven', "haven't", 'isn', "isn't", 'ma', 'mightn', "mightn't", 'mustn', "mustn't", 'needn', "needn't", 'shan', "shan't", 'shouldn', "shouldn't", 'wasn', "wasn't", 'weren', "weren't", 'won', "won't", 'wouldn', "wouldn't"]

View File

@@ -0,0 +1,137 @@
"""
01_gestor_paquetes.py
"""
import requests
from collections import Counter
import statistics
import pandas as pd
from bs4 import BeautifulSoup
# 1. Lee esta URL y encuentra las 10 palabras más frecuentes.
# Romeo y Julieta: 'http://www.gutenberg.org/files/1112/1112.txt'
url_romeo_julieta = 'http://www.gutenberg.org/files/1112/1112.txt'
response_romeo_julieta = requests.get(url_romeo_julieta)
words = response_romeo_julieta.text.split()
word_counts = Counter(words)
top_10_words = word_counts.most_common(10)
print("10 palabras más frecuentes:")
for word, count in top_10_words:
print(word, "-", count)
print()
# 2. Lee la API de gatos y la URL:
# 'https://api.thecatapi.com/v1/breeds'
# y encuentra:
url_gatos = 'https://api.thecatapi.com/v1/breeds'
response_gatos = requests.get(url_gatos)
data_gatos = response_gatos.json()
# - El mínimo, máximo, promedio,
# mediana y desviación estándar
# del peso de los gatos en unidades métricas.
weights = [cat['weight']['metric'] for cat in data_gatos]
weights = [float(w.split()[0]) for w in weights]
min_weight = min(weights)
max_weight = max(weights)
avg_weight = statistics.mean(weights)
med_weight = statistics.median(weights)
std_weight = statistics.stdev(weights)
print("Peso de los gatos en unidades métricas:")
print("Mínimo:", min_weight)
print("Máximo:", max_weight)
print("Promedio:", avg_weight)
print("Mediana:", med_weight)
print("Desviación estándar:", std_weight)
print()
# - El mínimo, máximo, promedio,
# mediana y desviación estándar
# de la esperanza de vida
# de los gatos en años.
lifespans = [cat['life_span'] for cat in data_gatos]
lifespans = [int(l.split()[0]) for l in lifespans if l != '']
min_lifespan = min(lifespans)
max_lifespan = max(lifespans)
avg_lifespan = statistics.mean(lifespans)
med_lifespan = statistics.median(lifespans)
std_lifespan = statistics.stdev(lifespans)
print("Esperanza de vida de los gatos en años:")
print("Mínimo:", min_lifespan)
print("Máximo:", max_lifespan)
print("Promedio:", avg_lifespan)
print("Mediana:", med_lifespan)
print("Desviación estándar:", std_lifespan)
print()
# - Crea una tabla de frecuencias
# de países y razas de gatos.
country_counts = Counter([cat['origin']
for cat in data_gatos if cat['origin'] != ''])
breed_counts = Counter([cat['name'] for cat in data_gatos])
print("Tabla de frecuencias de países:")
print(pd.DataFrame.from_dict(country_counts, orient='index'))
print()
print("Tabla de frecuencias de razas:")
print(pd.DataFrame.from_dict(breed_counts, orient='index'))
print()
# 3. Lee la [API de países](https://restcountries.eu/rest/v2/all)
# y encuentra:
# El enlace está caído, uso otra versión
url_countries = 'https://restcountries.com/v3.1/all'
response_countries = requests.get(url_countries)
data_countries = response_countries.json()
# - Los 10 países más grandes.
df = pd.DataFrame(data_countries)
df['area'] = pd.to_numeric(df['area'])
largest_countries = df.nlargest(10, 'area')
print("Los 10 países más grandes:")
for country in largest_countries['name']:
print(country['common'])
print()
# - Los 10 idiomas más hablados.
most_spoken_languages = df.explode('languages').groupby(
'languages').size().nlargest(10)
print("Los 10 idiomas más hablados:")
print(most_spoken_languages)
print()
# - El número total de idiomas en la API de países.
total_languages = len(df.explode('languages')['languages'].unique())
print("Número total de idiomas en la API de países:", total_languages)
print()
# 4. La Universidad de California en Irvine (UCI)
# es uno de los lugares más comunes para obtener
# conjuntos de datos para ciencia de datos
# y aprendizaje automático.
# Lee el contenido de UCI
# (https://archive.ics.uci.edu/ml/datasets.php).
# Sin bibliotecas adicionales, puede ser difícil,
# por lo que puedes intentarlo con BeautifulSoup4.
url = 'https://archive.ics.uci.edu/ml/datasets.php'
response = requests.get(url)
soup = BeautifulSoup(response.content, 'html.parser')
links = [a['href'] for a in soup.find_all('a') if a.has_attr('href')]

View File

@@ -0,0 +1,25 @@
# Gestor de paquetes de Python
Documento original en inglés: [python package manager](https://github.com/Asabeneh/30-Days-Of-Python/blob/master/20_Day_Python_package_manager/20_python_package_manager.md)
## Ejercicios
1. Lee esta URL y encuentra las 10 palabras más frecuentes. Romeo y Julieta: 'http://www.gutenberg.org/files/1112/1112.txt'
2. Lee la API de gatos y la URL: 'https://api.thecatapi.com/v1/breeds' y encuentra:
- El mínimo, máximo, promedio, mediana y desviación estándar del peso de los gatos en unidades métricas.
- El mínimo, máximo, promedio, mediana y desviación estándar de la esperanza de vida de los gatos en años.
- Crea una tabla de frecuencias de países y razas de gatos.
3. Lee la [API de países](https://restcountries.eu/rest/v2/all) y encuentra:
- Los 10 países más grandes.
- Los 10 idiomas más hablados.
- El número total de idiomas en la API de países.
4. La Universidad de California en Irvine (UCI) es uno de los lugares más comunes para obtener conjuntos de datos para ciencia de datos y aprendizaje automático. Lee el contenido de UCI (https://archive.ics.uci.edu/ml/datasets.php). Sin bibliotecas adicionales, puede ser difícil, por lo que puedes intentarlo con BeautifulSoup4.
[Solución](01_gestor_paquetes.py)
[<< Day 19](../19_Manipulación_de_archivos/README.md) | [Day 21 >>](../21_Clases_y_objetos/README.md)

View File

@@ -0,0 +1,137 @@
"""
01_clases_objetos.py
"""
import statistics
# 1. Python tiene el módulo llamado estadísticas
# y podemos usar este módulo para realizar todos
# los cálculos estadísticos. Sin embargo,
# para aprender a crear funciones y reutilizar funciones,
# intentemos desarrollar un programa
# que calcule la medida de tendencia central de una muestra
# (media, mediana, moda) y la medida de variabilidad
# (rango, varianza, desviación estándar).
# Además de esas medidas, encuentra el mínimo, máximo,
# recuento, percentil y distribución de frecuencia de la muestra.
# Puedes crear una clase llamada Estadísticas
# y crear todas las funciones que realicen cálculos estadísticos
# como métodos para la clase Estadísticas.
class Estadisticas:
def __init__(self, data):
self.data = data
def count(self):
return len(self.data)
def sum(self):
return sum(self.data)
def min(self):
return min(self.data)
def max(self):
return max(self.data)
def range(self):
return max(self.data) - min(self.data)
def mean(self):
return statistics.mean(self.data)
def median(self):
return statistics.median(self.data)
def mode(self):
mode = statistics.mode(self.data)
count = self.data.count(mode)
return {'moda': mode, 'recuento': count}
def std(self):
return statistics.stdev(self.data)
def var(self):
return statistics.variance(self.data)
def freq_dist(self):
freq = {}
for value in self.data:
freq[value] = freq.get(value, 0) + 1
freq_dist = [(freq[value], value) for value in freq]
freq_dist.sort(reverse=True)
return freq_dist
edades = [
31, 26, 34, 37, 27,
26, 32, 32, 26, 27,
27, 24, 32, 33, 27,
25, 26, 38, 37, 31,
34, 24, 33, 29, 26
]
estadisticas = Estadisticas(edades)
print('Recuento:', estadisticas.count())
print('Suma: ', estadisticas.sum())
print('Mínimo: ', estadisticas.min())
print('Máximo: ', estadisticas.max())
print('Rango: ', estadisticas.range())
print('Media: ', estadisticas.mean())
print('Mediana: ', estadisticas.median())
print('Moda:')
for key, value in estadisticas.mode().items():
print(f'\t - {key}: {value}')
print('Desviación Estándar: ', estadisticas.std())
print('Varianza: ', estadisticas.var())
freq_dist = estadisticas.freq_dist()
print('Distribución de Frecuencia:')
for freq, value in freq_dist:
print(f'\t - {freq}, {value}')
print()
# 2. Crea una clase llamada CuentaPersona.
# Tiene propiedades de nombre, apellido,
# ingresos, gastos y tiene métodos de total_ingreso,
# total_gasto, info_cuenta, agregar_ingreso,
# agregar_gasto y saldo_cuenta.
# Ingresos es un conjunto de ingresos y su descripción.
# Lo mismo ocurre con los gastos.
class CuentaPersona:
def __init__(self, nombre, apellido):
self.nombre = nombre
self.apellido = apellido
self.ingresos = {}
self.gastos = {}
def total_ingreso(self):
return sum(self.ingresos.values())
def total_gasto(self):
return sum(self.gastos.values())
def info_cuenta(self):
print(f'Nombre: {self.nombre} {self.apellido}')
print(f'Total de ingresos: {self.total_ingreso()}')
print(f'Total de gastos: {self.total_gasto()}')
print(f'Saldo de cuenta: {self.total_ingreso() - self.total_gasto()}')
def agregar_ingreso(self, descripcion, monto):
self.ingresos[descripcion] = monto
def agregar_gasto(self, descripcion, monto):
self.gastos[descripcion] = monto
def saldo_cuenta(self):
return self.total_ingreso() - self.total_gasto()
cuenta = CuentaPersona('Juan', 'Pérez')
cuenta.agregar_ingreso('Salario', 5000)
cuenta.agregar_ingreso('Venta de acciones', 2000)
cuenta.agregar_gasto('Alquiler', 1500)
cuenta.agregar_gasto('Comida', 500)
cuenta.info_cuenta()

View File

@@ -0,0 +1,49 @@
# Clases y objetos
Documento original en inglés: [Classes and Objects](https://github.com/Asabeneh/30-Days-Of-Python/blob/master/21_Day_Classes_and_objects/21_classes_and_objects.md)
## Ejercicios
### Ejercicios: Nivel 1
1. Python tiene el módulo llamado estadísticas y podemos usar este módulo para realizar todos los cálculos estadísticos. Sin embargo, para aprender a crear funciones y reutilizar funciones, intentemos desarrollar un programa que calcule la medida de tendencia central de una muestra (media, mediana, moda) y la medida de variabilidad (rango, varianza, desviación estándar). Además de esas medidas, encuentra el mínimo, máximo, recuento, percentil y distribución de frecuencia de la muestra. Puedes crear una clase llamada Estadísticas y crear todas las funciones que realicen cálculos estadísticos como métodos para la clase Estadísticas. Mira la salida a continuación.
```python
edades = [31, 26, 34, 37, 27, 26, 32, 32, 26, 27, 27, 24, 32, 33, 27, 25, 26, 38, 37, 31, 34, 24, 33, 29, 26]
print('Recuento:', data.count()) # 25
print('Suma: ', data.sum()) # 744
print('Mínimo: ', data.min()) # 24
print('Máximo: ', data.max()) # 38
print('Rango: ', data.range()) # 14
print('Media: ', data.mean()) # 30
print('Mediana: ', data.median()) # 29
print('Moda: ', data.mode()) # {'moda': 26, 'recuento': 5}
print('Desviación Estándar: ', data.std()) # 4.2
print('Varianza: ', data.var()) # 17.5
print('Distribución de Frecuencia: ', data.freq_dist()) # [(20.0, 26), (16.0, 27), (12.0, 32), (8.0, 37), (8.0, 34), (8.0, 33), (8.0, 31), (8.0, 24), (4.0, 38), (4.0, 29), (4.0, 25)]
```
```python
# Tu resultado debería lucir de la siguiente manera
print(data.describe())
Recuento: 25
Suma: 744
Mínimo: 24
Máximo: 38
Rango: 14
Media: 30
Mediana: 29
Moda: (26, 5)
Varianza: 17.5
Desviación Estándar: 4.2
Distribución de Frecuencia: [(20.0, 26), (16.0, 27), (12.0, 32), (8.0, 37), (8.0, 34), (8.0, 33), (8.0, 31), (8.0, 24), (4.0, 38), (4.0, 29), (4.0, 25)]
```
### Ejercicios: Nivel 2
1. Crea una clase llamada CuentaPersona. Tiene propiedades de nombre, apellido, ingresos, gastos y tiene métodos de total_ingreso, total_gasto, info_cuenta, agregar_ingreso, agregar_gasto y saldo_cuenta. Ingresos es un conjunto de ingresos y su descripción. Lo mismo ocurre con los gastos.
[Solución](01_clases_objetos.py)
[<< Day 20](../20_Gestor_de_paquetes_de_Python/README.md) | [Day 22 >>](../22_Web_scraping/README.md)

View File

@@ -0,0 +1,32 @@
import requests
from bs4 import BeautifulSoup
import json
# 1. Realiza un raspado web del siguiente sitio web
# y guarda los datos en un archivo JSON
# (URL = 'http://www.bu.edu/president/boston-university-facts-stats/').
url = 'http://www.bu.edu/president/boston-university-facts-stats/'
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
data = {}
for item in soup.find_all('div', {'class': 'facts-wrapper'}):
section_name = item.find('h5').get_text().strip()
section_data = {}
for li in item.find_all('li'):
key = li.find('p', {'class': 'text'}).get_text().strip()
value = li.find('span', {'class': 'value'}).get_text().strip()
section_data[key] = value
data[section_name] = section_data
with open('bu_stats.json', 'w') as f:
json.dump(data, f, indent=2)
print("Datos guardados en bu_stats.json")

View File

@@ -0,0 +1,34 @@
"""
01_web_scraping.py
"""
import requests
from bs4 import BeautifulSoup
import json
# 2. Extrae la tabla de esta URL
# (https://archive.ics.uci.edu/ml/datasets.php)
# y conviértela en un archivo JSON.
url = 'https://archive.ics.uci.edu/'
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
data = {}
for section in soup.find_all('section', class_='rounded-box'):
section_name = section.h1.get_text().strip()
section_data = {}
for div in section.find_all('div', class_='rounded-box'):
key = div.find('a', {'class': 'link-hover'}).get_text().strip()
value = div.find('p', {'class': 'truncate'}).get_text().strip()
section_data[key] = value
data[section_name] = section_data
with open('uci_datasets.json', 'w') as f:
json.dump(data, f, indent=2)
print("Datos guardados en uci_datasets.json")

View File

@@ -0,0 +1,41 @@
import requests
from bs4 import BeautifulSoup
import json
url = 'https://en.wikipedia.org/wiki/List_of_presidents_of_the_United_States'
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
# Encuentra la tabla por su clase
table = soup.find('table', {'class': 'wikitable'})
# Encuentra todas las filas en la tabla
rows = table.find_all('tr')
# Extrae los encabezados de la primera fila
headers = [header.get_text().strip()
for header in rows[0].find_all(['th', 'td'])]
# Inicializa una lista para almacenar los datos
data = []
# Itera a través de las filas a partir de la segunda (índice 1)
for row in rows[1:]:
# Encuentra todas las celdas en la fila
cells = row.find_all(['th', 'td'])
# Verifica que haya celdas suficientes en la fila
if cells and len(cells) >= len(headers):
president = {}
for i, header in enumerate(headers):
# Asigna el valor de la celda al encabezado correspondiente
cell_data = cells[i].find(string=True) if cells[i].find(
string=True) else cells[i].find('a')['title'].strip()
president[header.lower()] = cell_data
data.append(president)
# Guarda los datos como JSON
with open('us_presidents.json', 'w') as f:
json.dump(data, f, indent=2)
print("Datos guardados en us_presidents.json")

View File

@@ -0,0 +1,19 @@
# Web scraping
Documento original en inglés: [Web Scraping](https://github.com/Asabeneh/30-Days-Of-Python/blob/master/22_Day_Web_scraping/22_web_scraping.md)
## Ejercicios
1. Realiza un raspado web del siguiente sitio web y guarda los datos en un archivo JSON (URL = 'http://www.bu.edu/president/boston-university-facts-stats/').
[Solución](01_web_scraping.py)
2. Extrae la tabla de esta URL (https://archive.ics.uci.edu/ml/datasets.php) y conviértela en un archivo JSON.
[Solución](02_web_scraping.py)
3. Realiza un raspado web de la tabla de presidentes y guarda los datos como JSON (https://en.wikipedia.org/wiki/List_of_presidents_of_the_United_States). La tabla no está muy estructurada y el proceso de raspado puede llevar mucho tiempo.
[Solución](03_web_scraping.py)
[<< Day 21](../21_Clases_y_objetos/README.md) | [Day 23 >>](../23_Entorno_virtual/README.md)

View File

@@ -0,0 +1,65 @@
{
"Community": {
"Student Body": "37,557",
"Living Alumni": "431,000+",
"Total Employees": "10,674",
"Faculty": "4,309",
"Nondegree Students": "1,337",
"Graduate & Professional Students": "18,476",
"Undergraduate Students": "17,744"
},
"Campus": {
"Classrooms": "848",
"Buildings": "343",
"Laboratories": "1,481",
"Libraries": "13",
"Campus Area (acres)": "140"
},
"Academics": {
"Study Abroad Programs": "80+",
"Average Class Size": "30",
"Faculty": "4,309",
"Student/Faculty Ratio": "11:1",
"Schools and Colleges": "17",
"Programs of Study": "300+"
},
"Grant & Contract Awards": {
"Research Expenditures (FY22)": "$630.7M",
"Research Awards": "$674M",
"BMC Clinical Research Grants (FY22)": "$82M"
},
"Undergraduate Financial Aid & Scholarships": {
"Average Total Need-Based Financial Aid": "$57,237",
"Average Need-Based Grant/Scholarship": "$53,029",
"Grants & Scholarships (need-based)": "$388.4M",
"Grants & Scholarships (non-need-based)": "$26.5M"
},
"Student Life": {
"Community Service Hours": "130,000+",
"Alternative Service Breaks Participants": "65+",
"BU on Social": "new accounts daily",
"Cultural & Religious Organizations": "80+",
"Community Service & Justice Organizations": "70+",
"Academic & Professional Organizations": "140+",
"Art & Performance Organizations": "60+",
"Student Organizations": "450+",
"First-Year Student Outreach Project Volunteers": "400+"
},
"Research": {
"Faculty Publications": "7,000+",
"Student UROP Participants": "450+",
"Centers & Institutes": "130+"
},
"International Community": {
"Global Initiatives": "300+",
"Cultural Student Groups": "60+",
"Alumni Countries": "180+",
"International Students": "10,000+"
},
"Athletics": {
"Intramural Sports & Tournaments": "12+",
"Club and Intramural Sports Participants": "7,000+",
"Club Sports": "36",
"Varsity Sports": "24"
}
}

View File

@@ -0,0 +1,18 @@
{
"Popular Datasets": {
"Iris": "A small classic dataset from Fisher, 1936. One of the earliest known datasets used for evaluating classification methods.",
"Heart Disease": "4 databases: Cleveland, Hungary, Switzerland, and the VA Long Beach",
"Adult": "Predict whether income exceeds $50K/yr based on census data. Also known as \"Census Income\" dataset.",
"Wine": "Using chemical analysis to determine the origin of wines",
"Dry Bean Dataset": "Images of 13,611 grains of 7 different registered dry beans were taken with a high-resolution camera. A total of 16 features; 12 dimensions and 4 shape forms, were obtained from the grains.",
"Diabetes": "This diabetes dataset is from AIM '94"
},
"New Datasets": {
"TCGA Kidney Cancers": "The TCGA Kidney Cancers Dataset is a bulk RNA-seq dataset that contains transcriptome profiles of patients diagnosed with three different subtypes of kidney cancers. This dataset can be used to make predictions about the specific subtype of kidney cancers given the normalized transcriptome profile data, as well as providing a hands-on experience on large and sparse genomic information.",
"CDC Diabetes Health Indicators": "The Diabetes Health Indicators Dataset contains healthcare statistics and lifestyle survey information about people in general along with their diagnosis of diabetes. The 35 features consist of some demographics, lab test results, and answers to survey questions for each patient. The target variable for classification is whether a patient has diabetes, is pre-diabetic, or healthy.",
"AIDS Clinical Trials Group Study 175": "The AIDS Clinical Trials Group Study 175 Dataset contains healthcare statistics and categorical information about patients who have been diagnosed with AIDS. This dataset was initially published in 1996. The prediction task is to predict whether or not each patient died within a certain window of time or not.",
"National Health and Nutrition Health Survey 2013-2014 (NHANES) Age Prediction Subset": "The National Health and Nutrition Examination Survey (NHANES), administered by the Centers for Disease Control and Prevention (CDC), collects extensive health and nutritional information from a diverse U.S. population. Though expansive, the dataset is often too broad for specific analytical purposes. In this sub-dataset, we narrow our focus to predicting respondents' age by extracting a subset of features from the larger NHANES dataset. These selected features include physiological measurements, lifestyle choices, and biochemical markers, which were hypothesized to have strong correlations with age.",
"Large-scale Wave Energy Farm": "Wave energy is a rapidly advancing and promising renewable energy source that holds great potential for addressing the challenges of global warming and climate change. However, optimizing energy output in large wave farms presents a complex problem due to the expensive calculations required to account for hydrodynamic interactions between wave energy converters (WECs). Developing a fast and accurate surrogate model is crucial to overcome these challenges. In light of this, we have compiled an extensive WEC dataset that includes 54,000 and 9,600 configurations involving 49 and 100 WECs, coordination, power, q-factor, and total farm power output. The dataset was derived from a study published at the GECCO conference and received the prestigious Best Paper award. We want to acknowledge the support of the University of Adelaide Phoenix HPC service in conducting this research. For more details, please refer to the following link: https://dl.acm.org/doi/abs/10.1145/3377930.3390235.",
"SUPPORT2": "This dataset comprises 9105 individual critically ill patients across 5 United States medical centers, accessioned throughout 1989-1991 and 1992-1994.\nEach row concerns hospitalized patient records who met the inclusion and exclusion criteria for nine disease categories: acute respiratory failure, chronic obstructive pulmonary disease, congestive heart failure, liver disease, coma, colon cancer, lung cancer, multiple organ system failure with malignancy, and multiple organ system failure with sepsis. The goal is to determine these patients' 2- and 6-month survival rates based on several physiologic, demographics, and disease severity information. \nIt is an important problem because it addresses the growing national concern over patients' loss of control near the end of life. It enables earlier decisions and planning to reduce the frequency of a mechanical, painful, and prolonged dying process."
}
}

View File

@@ -0,0 +1,416 @@
[
{
"no.[a]": "1",
"portrait": "\n",
"name(birth\u2013death)": "George Washington",
"term[14]": "April 30, 1789",
"party[b][15]": "\n",
"election": "Unaffiliated",
"vice president[16]": "1788\u20131789"
},
{
"no.[a]": "2",
"portrait": "\n",
"name(birth\u2013death)": "John Adams",
"term[14]": "March 4, 1797",
"party[b][15]": "\n",
"election": "Federalist",
"vice president[16]": "1796"
},
{
"no.[a]": "3",
"portrait": "\n",
"name(birth\u2013death)": "Thomas Jefferson",
"term[14]": "March 4, 1801",
"party[b][15]": "\n",
"election": "Democratic-",
"vice president[16]": "1800"
},
{
"no.[a]": "4",
"portrait": "\n",
"name(birth\u2013death)": "James Madison",
"term[14]": "March 4, 1809",
"party[b][15]": "\n",
"election": "Democratic-",
"vice president[16]": "1808"
},
{
"no.[a]": "5",
"portrait": "\n",
"name(birth\u2013death)": "James Monroe",
"term[14]": "March 4, 1817",
"party[b][15]": "\n",
"election": "Democratic-",
"vice president[16]": "1816"
},
{
"no.[a]": "6",
"portrait": "\n",
"name(birth\u2013death)": "John Quincy Adams",
"term[14]": "March 4, 1825",
"party[b][15]": "\n",
"election": "Democratic-",
"vice president[16]": "1824"
},
{
"no.[a]": "7",
"portrait": "\n",
"name(birth\u2013death)": "Andrew Jackson",
"term[14]": "March 4, 1829",
"party[b][15]": "\n",
"election": "Democratic",
"vice president[16]": "1828"
},
{
"no.[a]": "8",
"portrait": "\n",
"name(birth\u2013death)": "Martin Van Buren",
"term[14]": "March 4, 1837",
"party[b][15]": "\n",
"election": "Democratic",
"vice president[16]": "1836"
},
{
"no.[a]": "9",
"portrait": "\n",
"name(birth\u2013death)": "William Henry Harrison",
"term[14]": "March 4, 1841",
"party[b][15]": "\n",
"election": "Whig",
"vice president[16]": "1840"
},
{
"no.[a]": "10",
"portrait": "\n",
"name(birth\u2013death)": "John Tyler",
"term[14]": "April 4, 1841",
"party[b][15]": "\n",
"election": "Whig",
"vice president[16]": "\u2013"
},
{
"no.[a]": "11",
"portrait": "\n",
"name(birth\u2013death)": "James K. Polk",
"term[14]": "March 4, 1845",
"party[b][15]": "\n",
"election": "Democratic",
"vice president[16]": "1844"
},
{
"no.[a]": "12",
"portrait": "\n",
"name(birth\u2013death)": "Zachary Taylor",
"term[14]": "March 4, 1849",
"party[b][15]": "\n",
"election": "Whig",
"vice president[16]": "1848"
},
{
"no.[a]": "13",
"portrait": "\n",
"name(birth\u2013death)": "Millard Fillmore",
"term[14]": "July 9, 1850",
"party[b][15]": "\n",
"election": "Whig",
"vice president[16]": "\u2013"
},
{
"no.[a]": "14",
"portrait": "\n",
"name(birth\u2013death)": "Franklin Pierce",
"term[14]": "March 4, 1853",
"party[b][15]": "\n",
"election": "Democratic",
"vice president[16]": "1852"
},
{
"no.[a]": "15",
"portrait": "\n",
"name(birth\u2013death)": "James Buchanan",
"term[14]": "March 4, 1857",
"party[b][15]": "\n",
"election": "Democratic",
"vice president[16]": "1856"
},
{
"no.[a]": "16",
"portrait": "\n",
"name(birth\u2013death)": "Abraham Lincoln",
"term[14]": "March 4, 1861",
"party[b][15]": "\n",
"election": "Republican",
"vice president[16]": "1860"
},
{
"no.[a]": "17",
"portrait": "\n",
"name(birth\u2013death)": "Andrew Johnson",
"term[14]": "April 15, 1865",
"party[b][15]": "\n",
"election": "National Union",
"vice president[16]": "\u2013"
},
{
"no.[a]": "18",
"portrait": "\n",
"name(birth\u2013death)": "Ulysses S. Grant",
"term[14]": "March 4, 1869",
"party[b][15]": "\n",
"election": "Republican",
"vice president[16]": "1868"
},
{
"no.[a]": "19",
"portrait": "\n",
"name(birth\u2013death)": "Rutherford B. Hayes",
"term[14]": "March 4, 1877",
"party[b][15]": "\n",
"election": "Republican",
"vice president[16]": "1876"
},
{
"no.[a]": "20",
"portrait": "\n",
"name(birth\u2013death)": "James A. Garfield",
"term[14]": "March 4, 1881",
"party[b][15]": "\n",
"election": "Republican",
"vice president[16]": "1880"
},
{
"no.[a]": "21",
"portrait": "\n",
"name(birth\u2013death)": "Chester A. Arthur",
"term[14]": "September 19, 1881",
"party[b][15]": "\n",
"election": "Republican",
"vice president[16]": "\u2013"
},
{
"no.[a]": "22",
"portrait": "\n",
"name(birth\u2013death)": "Grover Cleveland",
"term[14]": "March 4, 1885",
"party[b][15]": "\n",
"election": "Democratic",
"vice president[16]": "1884"
},
{
"no.[a]": "23",
"portrait": "\n",
"name(birth\u2013death)": "Benjamin Harrison",
"term[14]": "March 4, 1889",
"party[b][15]": "\n",
"election": "Republican",
"vice president[16]": "1888"
},
{
"no.[a]": "24",
"portrait": "\n",
"name(birth\u2013death)": "Grover Cleveland",
"term[14]": "March 4, 1893",
"party[b][15]": "\n",
"election": "Democratic",
"vice president[16]": "1892"
},
{
"no.[a]": "25",
"portrait": "\n",
"name(birth\u2013death)": "William McKinley",
"term[14]": "March 4, 1897",
"party[b][15]": "\n",
"election": "Republican",
"vice president[16]": "1896"
},
{
"no.[a]": "26",
"portrait": "\n",
"name(birth\u2013death)": "Theodore Roosevelt",
"term[14]": "September 14, 1901",
"party[b][15]": "\n",
"election": "Republican",
"vice president[16]": "\u2013"
},
{
"no.[a]": "27",
"portrait": "\n",
"name(birth\u2013death)": "William Howard Taft",
"term[14]": "March 4, 1909",
"party[b][15]": "\n",
"election": "Republican",
"vice president[16]": "1908"
},
{
"no.[a]": "28",
"portrait": "\n",
"name(birth\u2013death)": "Woodrow Wilson",
"term[14]": "March 4, 1913",
"party[b][15]": "\n",
"election": "Democratic",
"vice president[16]": "1912"
},
{
"no.[a]": "29",
"portrait": "\n",
"name(birth\u2013death)": "Warren G. Harding",
"term[14]": "March 4, 1921",
"party[b][15]": "\n",
"election": "Republican",
"vice president[16]": "1920"
},
{
"no.[a]": "30",
"portrait": "\n",
"name(birth\u2013death)": "Calvin Coolidge",
"term[14]": "August 2, 1923",
"party[b][15]": "\n",
"election": "Republican",
"vice president[16]": "\u2013"
},
{
"no.[a]": "31",
"portrait": "\n",
"name(birth\u2013death)": "Herbert Hoover",
"term[14]": "March 4, 1929",
"party[b][15]": "\n",
"election": "Republican",
"vice president[16]": "1928"
},
{
"no.[a]": "32",
"portrait": "\n",
"name(birth\u2013death)": "Franklin D. Roosevelt",
"term[14]": "March 4, 1933",
"party[b][15]": "\n",
"election": "Democratic",
"vice president[16]": "1932"
},
{
"no.[a]": "33",
"portrait": "\n",
"name(birth\u2013death)": "Harry S. Truman",
"term[14]": "April 12, 1945",
"party[b][15]": "\n",
"election": "Democratic",
"vice president[16]": "\u2013"
},
{
"no.[a]": "34",
"portrait": "\n",
"name(birth\u2013death)": "Dwight D. Eisenhower",
"term[14]": "January 20, 1953",
"party[b][15]": "\n",
"election": "Republican",
"vice president[16]": "1952"
},
{
"no.[a]": "35",
"portrait": "\n",
"name(birth\u2013death)": "John F. Kennedy",
"term[14]": "January 20, 1961",
"party[b][15]": "\n",
"election": "Democratic",
"vice president[16]": "1960"
},
{
"no.[a]": "36",
"portrait": "\n",
"name(birth\u2013death)": "Lyndon B. Johnson",
"term[14]": "November 22, 1963",
"party[b][15]": "\n",
"election": "Democratic",
"vice president[16]": "\u2013"
},
{
"no.[a]": "37",
"portrait": "\n",
"name(birth\u2013death)": "Richard Nixon",
"term[14]": "January 20, 1969",
"party[b][15]": "\n",
"election": "Republican",
"vice president[16]": "1968"
},
{
"no.[a]": "38",
"portrait": "\n",
"name(birth\u2013death)": "Gerald Ford",
"term[14]": "August 9, 1974",
"party[b][15]": "\n",
"election": "Republican",
"vice president[16]": "\u2013"
},
{
"no.[a]": "39",
"portrait": "\n",
"name(birth\u2013death)": "Jimmy Carter",
"term[14]": "January 20, 1977",
"party[b][15]": "\n",
"election": "Democratic",
"vice president[16]": "1976"
},
{
"no.[a]": "40",
"portrait": "\n",
"name(birth\u2013death)": "Ronald Reagan",
"term[14]": "January 20, 1981",
"party[b][15]": "\n",
"election": "Republican",
"vice president[16]": "1980"
},
{
"no.[a]": "41",
"portrait": "\n",
"name(birth\u2013death)": "George H. W. Bush",
"term[14]": "January 20, 1989",
"party[b][15]": "\n",
"election": "Republican",
"vice president[16]": "1988"
},
{
"no.[a]": "42",
"portrait": "\n",
"name(birth\u2013death)": "Bill Clinton",
"term[14]": "January 20, 1993",
"party[b][15]": "\n",
"election": "Democratic",
"vice president[16]": "1992"
},
{
"no.[a]": "43",
"portrait": "\n",
"name(birth\u2013death)": "George W. Bush",
"term[14]": "January 20, 2001",
"party[b][15]": "\n",
"election": "Republican",
"vice president[16]": "2000"
},
{
"no.[a]": "44",
"portrait": "\n",
"name(birth\u2013death)": "Barack Obama",
"term[14]": "January 20, 2009",
"party[b][15]": "\n",
"election": "Democratic",
"vice president[16]": "2008"
},
{
"no.[a]": "45",
"portrait": "\n",
"name(birth\u2013death)": "Donald Trump",
"term[14]": "January 20, 2017",
"party[b][15]": "\n",
"election": "Republican",
"vice president[16]": "2016"
},
{
"no.[a]": "46",
"portrait": "\n",
"name(birth\u2013death)": "Joe Biden",
"term[14]": "January 20, 2021",
"party[b][15]": "\n",
"election": "Democratic",
"vice president[16]": "2020"
}
]

View File

@@ -0,0 +1 @@
venv

View File

@@ -0,0 +1,57 @@
# Entorno virtual
Documento original en inglés: [Virtual Environment](https://github.com/Asabeneh/30-Days-Of-Python/blob/master/23_Day_Virtual_environment/23_virtual_environment.md)
## Ejercicios
1. Crea un directorio de proyecto con un entorno virtual basado en el ejemplo dado arriba.
Solución:
Instalar la herramienta virtualenv con el comando:
```
pip install virtualenv
```
Crear carpeta para proyecto de Flask:
```
mkdir flask_project
```
Crear entorno virtual dentro de la carpeta flask_project:
```
cd flask_project
virtualenv venv
```
El comando `virtualenv venv` crea un nuevo entorno virtual llamado `venv` dentro de la carpeta `flask_project`.
Activar el entorno virtual:
```
source venv/bin/activate
```
Después de activar el entorno virtual, deberías ver (venv) al principio de la línea de comandos en la terminal. Esto indica que el entorno virtual está activo. En mi caso tengo el nombre del entorno virtual con zsh en la derecha.
Instalar Flask en el entorno virtual:
```
pip install Flask
```
Verificar que se haya instalado correctamente escribiendo el siguiente comando:
```
pip freeze
```
![](pic/venv.png)
Al terminar se debes desactivar el entorno virtual:
```
deactivate
```
Incluir la carpeta venv en el archivo [.gitignore](.gitignore) para evitar subirla al repositorio remoto.
[<< Day 22](../22_Web_scraping/README.md) | [Day 24 >>](../24_Estadísticas/README.md)

Binary file not shown.

After

Width:  |  Height:  |  Size: 107 KiB

View File

@@ -0,0 +1,358 @@
"""
01_stats.py
"""
import numpy as np
# Info numpy
print('numpy version:', np.__version__)
print()
print(dir(np))
print()
# Creating int numpy arrays
python_list = [1, 2, 3, 4, 5]
print('Type: ', type(python_list))
two_dimensional_list = [[0, 1, 2], [3, 4, 5], [6, 7, 8]]
print(two_dimensional_list)
numpy_array_from_list = np.array(python_list)
print(type(numpy_array_from_list))
print(numpy_array_from_list)
print()
# Creating float numpy arrays
python_list = [1, 2, 3, 4, 5]
numy_array_from_list2 = np.array(python_list, dtype=float)
print(numy_array_from_list2)
print()
# Creating boolean numpy arrays
numpy_bool_array = np.array([0, 1, -1, 0, 0], dtype=bool)
print(numpy_bool_array)
print()
# Creating multidimensional array using numpy
numpy_two_dimensional_list = np.array(two_dimensional_list)
print(type(numpy_two_dimensional_list))
print(numpy_two_dimensional_list)
print()
# Converting numpy array to list
np_to_list = numpy_array_from_list.tolist()
print(type(np_to_list))
print('one dimensional array:', np_to_list)
print('two dimensional array: ', numpy_two_dimensional_list.tolist())
print()
# Creating numpy array from tuple
python_tuple = (1, 2, 3, 4, 5)
print(type(python_tuple))
print('python_tuple: ', python_tuple)
numpy_array_from_tuple = np.array(python_tuple)
print(type(numpy_array_from_tuple))
print('numpy_array_from_tuple: ', numpy_array_from_tuple)
print()
# Shape of numpy array
nums = np.array([1, 2, 3, 4, 5])
print(nums)
print('shape of nums: ', nums.shape)
print(numpy_two_dimensional_list)
print('shape of numpy_two_dimensional_list: ',
numpy_two_dimensional_list.shape)
three_by_four_array = np.array([[0, 1, 2, 3],
[4, 5, 6, 7],
[8, 9, 10, 11]])
print(three_by_four_array.shape)
print()
# Data type of numpy array
int_lists = [-3, -2, -1, 0, 1, 2, 3]
int_array = np.array(int_lists)
float_array = np.array(int_lists, dtype=float)
print(int_array)
print(int_array.dtype)
print(float_array)
print(float_array.dtype)
print()
# Size of a numpy array
numpy_array_from_list = np.array([1, 2, 3, 4, 5])
two_dimensional_list = np.array([[0, 1, 2],
[3, 4, 5],
[6, 7, 8]])
print('The size:', numpy_array_from_list.size)
print('The size:', two_dimensional_list.size)
print()
# Mathematical Operation using numpy
# Addition
print('original array: ', numpy_array_from_list)
ten_plus_original = numpy_array_from_list + 10
print(ten_plus_original)
print()
# Subtraction
print('original array: ', numpy_array_from_list)
ten_minus_original = numpy_array_from_list - 10
print(ten_minus_original)
print()
# Multiplication
print('original array: ', numpy_array_from_list)
ten_times_original = numpy_array_from_list * 10
print(ten_times_original)
print()
# Division
print('original array: ', numpy_array_from_list)
ten_times_original = numpy_array_from_list / 10
print(ten_times_original)
print()
# Modulus
print('original array: ', numpy_array_from_list)
ten_times_original = numpy_array_from_list % 3
print(ten_times_original)
print()
# Floor division
print('original array: ', numpy_array_from_list)
ten_times_original = numpy_array_from_list // 10
print(ten_times_original)
print()
# Exponential
print('original array: ', numpy_array_from_list)
ten_times_original = numpy_array_from_list ** 2
print(ten_times_original)
print()
# Int, Float numbers
numpy_int_arr = np.array([1, 2, 3, 4])
numpy_float_arr = np.array([1.1, 2.0, 3.2])
numpy_bool_arr = np.array([-3, -2, 0, 1, 2, 3], dtype='bool')
print(numpy_int_arr.dtype)
print(numpy_float_arr.dtype)
print(numpy_bool_arr.dtype)
print()
# Converting types
# int to float
numpy_int_arr = np.array([1, 2, 3, 4], dtype='float')
print(numpy_int_arr)
print()
# float to int
numpy_int_arr = np.array(numpy_int_arr, dtype='int')
print(numpy_int_arr)
print()
# float to bool
numpy_int_arr = np.array([-3, -2, 0, 1, 2, 3], dtype='bool')
print(numpy_int_arr)
print()
# int to str
numpy_int_arr = np.array([1, 2, 3, 4], dtype='str')
print(numpy_int_arr)
print()
# Multi-dimensional Arrays
# 2 Dimension Array
two_dimension_array = np.array([
(1, 2, 3),
(4, 5, 6),
(7, 8, 9)
])
print(type(two_dimension_array))
print(two_dimension_array)
print('Shape: ', two_dimension_array.shape)
print('Size:', two_dimension_array.size)
print('Data type:', two_dimension_array.dtype)
print()
# Getting items from a numpy array
# 2 Dimension Array
two_dimension_array = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
first_row = two_dimension_array[0]
second_row = two_dimension_array[1]
third_row = two_dimension_array[2]
print('First row:', first_row)
print('Second row:', second_row)
print('Third row: ', third_row)
print()
first_column = two_dimension_array[:, 0]
second_column = two_dimension_array[:, 1]
third_column = two_dimension_array[:, 2]
print('First column:', first_column)
print('Second column:', second_column)
print('Third column: ', third_column)
print(two_dimension_array)
print()
# Slicing Numpy array
first_two_rows_and_columns = two_dimension_array[0:2, 0:2]
print(first_two_rows_and_columns)
print()
# How to reverse the rows and the whole array?
print(two_dimension_array[::])
print()
# Reverse the row and column positions
print(two_dimension_array[::-1, ::-1])
print()
# How to represent missing values ?
print(two_dimension_array)
two_dimension_array[1, 1] = 55
two_dimension_array[1, 2] = 44
print(two_dimension_array)
print()
# Numpy Zeroes
# numpy.zeros(shape, dtype=float, order='C')
numpy_zeroes = np.zeros((3, 3), dtype=int, order='C')
print(numpy_zeroes)
print()
# Numpy Zeroes
numpy_ones = np.ones((3, 3), dtype=int, order='C')
print(numpy_ones)
print()
twoes = numpy_ones * 2
print(twoes)
print()
# Reshape
# numpy.reshape(), numpy.flatten()
first_shape = np.array([(1, 2, 3), (4, 5, 6)])
print(first_shape)
reshaped = first_shape.reshape(3, 2)
print(reshaped)
print()
flattened = reshaped.flatten()
print(flattened)
print()
# Horitzontal Stack
np_list_one = np.array([1, 2, 3])
np_list_two = np.array([4, 5, 6])
print(np_list_one + np_list_two)
print('Horizontal Append:', np.hstack((np_list_one, np_list_two)))
print()
# Vertical Stack
print('Vertical Append:', np.vstack((np_list_one, np_list_two)))
print()
# Generating Random Numbers
# Generate a random float number
random_float = np.random.random()
print(random_float)
print()
# Generate a random float number
random_floats = np.random.random(5)
print(random_floats)
print()
# Generating a random integers between 0 and 10
random_int = np.random.randint(0, 11)
print(random_int)
print()
# Generating a random integers between 2 and 11, and creating a one row array
random_int = np.random.randint(2, 10, size=4)
print(random_int)
print()
# Generating a random integers between 0 and 10
random_int = np.random.randint(2, 10, size=(3, 3))
print(random_int)
print()
# Generationg random numbers
# np.random.normal(mu, sigma, size)
normal_array = np.random.normal(79, 15, 80)
print(normal_array)
print()

View File

@@ -0,0 +1,274 @@
"""
02_stats.py
"""
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from scipy import stats
# Numpy and Statistics
# Matrix in numpy
four_by_four_matrix = np.matrix(np.ones((4, 4), dtype=float))
print(four_by_four_matrix)
np.asarray(four_by_four_matrix)[2] = 2
print(four_by_four_matrix)
print()
# Numpy numpy.arange()
# creating list using range(starting, stop, step)
lst = range(0, 11, 2)
print(lst)
print()
for l in lst:
print(l)
print()
# Similar to range arange numpy.arange(start, stop, step)
whole_numbers = np.arange(0, 20, 1)
print(whole_numbers)
print()
natural_numbers = np.arange(1, 20, 1)
print(natural_numbers)
print()
odd_numbers = np.arange(1, 20, 2)
print(odd_numbers)
print()
even_numbers = np.arange(2, 20, 2)
print(even_numbers)
print()
# Creating sequence of numbers using linspace
# numpy.linspace()
# numpy.logspace() in Python with Example
# For instance, it can be used to create 10 values from 1 to 5 evenly spaced.
print(np.linspace(1.0, 5.0, num=10))
print()
# not to include the last value in the interval
print(np.linspace(1.0, 5.0, num=5, endpoint=False))
print()
# LogSpace
# LogSpace returns even spaced numbers on a log scale. Logspace has the same parameters as np.linspace.
# Syntax:
# numpy.logspace(start, stop, num, endpoint)
print(np.logspace(2, 4.0, num=4))
print()
# to check the size of an array
x = np.array([1, 2, 3], dtype=np.complex128)
print(x)
print()
print(x.itemsize)
print()
# indexing and Slicing NumPy Arrays in Python
np_list = np.array([(1, 2, 3), (4, 5, 6)])
print(np_list)
print()
print('First row: ', np_list[0])
print('Second row: ', np_list[1])
print()
print('First column: ', np_list[:, 0])
print('Second column: ', np_list[:, 1])
print('Third column: ', np_list[:, 2])
print()
# NumPy Statistical Functions with Example
np_normal_dis = np.random.normal(5, 0.5, 100)
print(np_normal_dis)
print()
# min, max, mean, median, sd
two_dimension_array = np.array([
(1, 2, 3),
(4, 5, 6),
(7, 8, 9)
])
print('min: ', two_dimension_array.min())
print('max: ', two_dimension_array.max())
print('mean: ', two_dimension_array.mean())
# print('median: ', two_dimension_array.median())
print('sd: ', two_dimension_array.std())
print()
print(two_dimension_array)
print('Column with minimum: ', np.amin(two_dimension_array, axis=0))
print('Column with maximum: ', np.amax(two_dimension_array, axis=0))
print('=== Row ==')
print('Row with minimum: ', np.amin(two_dimension_array, axis=1))
print('Row with maximum: ', np.amax(two_dimension_array, axis=1))
print()
# How to create repeating sequences?
a = [1, 2, 3]
# Repeat whole of 'a' two times
print('Tile: ', np.tile(a, 2))
# Repeat each element of 'a' two times
print('Repeat: ', np.repeat(a, 2))
print()
# How to generate random numbers?
# One random number between [0,1)
one_random_num = np.random.random()
one_random_in = np.random
print(one_random_num)
print()
# Random numbers between [0,1) of shape 2,3
r = np.random.random(size=[2, 3])
print(r)
print()
print(np.random.choice(['a', 'e', 'i', 'o', 'u'], size=10))
print()
# Random numbers between [0, 1] of shape 2, 2
rand = np.random.rand(2, 2)
print(rand)
print()
rand2 = np.random.randn(2, 2)
print(rand2)
print()
# Random integers between [0, 10) of shape 2,5
rand_int = np.random.randint(0, 10, size=[5, 3])
print(rand_int)
print()
# mean, standard deviation, number of samples
np_normal_dis = np.random.normal(5, 0.5, 1000)
np_normal_dis
# min, max, mean, median, sd
print('min: ', np.min(np_normal_dis))
print('max: ', np.max(np_normal_dis))
print('mean: ', np.mean(np_normal_dis))
print('median: ', np.median(np_normal_dis))
print('mode: ', stats.mode(np_normal_dis))
print('sd: ', np.std(np_normal_dis))
print()
plt.hist(np_normal_dis, color="grey", bins=21)
plt.show()
print()
# Linear algebra
# Dot product: product of two arrays
f = np.array([1, 2, 3])
g = np.array([4, 5, 3])
# 1*4+2*5 + 3*6
dot_product = np.dot(f, g)
print(dot_product)
print()
# Matmul: matruc product of two arrays
h = [[1, 2], [3, 4]]
i = [[5, 6], [7, 8]]
# 1*5+2*7 = 19
matmul = np.matmul(h, i)
print(matmul)
print()
# Determinant 2*2 matrix
# 5*8-7*6np.linalg.det(i)
matri = np.linalg.det(i)
print(matri)
print()
Z = np.zeros((8, 8))
Z[1::2, ::2] = 1
Z[::2, 1::2] = 1
print(Z)
print()
new_list = [x + 2 for x in range(0, 11)]
print(new_list)
print()
np_arr = np.array(range(0, 11))
np_arr + 2
print(np_arr)
print()
temp = np.array([1, 2, 3, 4, 5])
pressure = temp * 2 + 5
print(pressure)
plt.plot(temp, pressure)
plt.xlabel('Temperature in oC')
plt.ylabel('Pressure in atm')
plt.title('Temperature vs Pressure')
plt.xticks(np.arange(0, 6, step=0.5))
plt.show()
mu = 28
sigma = 15
samples = 100000
x = np.random.normal(mu, sigma, samples)
ax = sns.distplot(x)
ax.set(xlabel="x", ylabel='y')
plt.show()

View File

@@ -0,0 +1,13 @@
# Estadísticas
Documento original en inglés: [statistics](https://github.com/Asabeneh/30-Days-Of-Python/blob/master/24_Day_Statistics/24_statistics.md)
## Ejercicios
1. Repite todos los [ejemplos](https://github.com/Asabeneh/30-Days-Of-Python/blob/master/24_Day_Statistics/24_statistics.md)
[Solución 01](01_stats.py)
[Solución 02](02_stats.py)
[<< Day 23](../23_Entorno_virtual/README.md) | [Day 25 >>](../25_Pandas/README.md)

View File

@@ -0,0 +1,43 @@
"""
01_pandas.py
"""
import pandas as pd
# 1. Lee el archivo hacker_news.csv del directorio de datos.
df = pd.read_csv('hacker_news.csv')
# 2. Obtén las primeras cinco filas.
print(df.head())
print()
# 3. Obtén las últimas cinco filas.
print(df.tail())
print()
# 4. Obtén la columna de títulos como una serie de pandas.
titles = df['title']
print(titles)
print()
# 5. Cuenta el número de filas y columnas.
print('Número de filas:', len(df))
print('Número de columnas:', len(df.columns))
print()
# Filtra los títulos que contengan "python".
python_titles = df[df['title'].str.contains('python', case=False)]
print(python_titles)
print()
# Filtra los títulos que contengan "JavaScript".
js_titles = df[df['title'].str.contains('JavaScript', case=False)]
print(js_titles)
print()
# Explora los datos y dales sentido.
# Puedes utilizar métodos como describe(), info(), value_counts(), etc. para explorar los datos y obtener estadísticas descriptivas.
print(df.describe())
print(df.info())
print(df['title'].value_counts())
print()

View File

@@ -0,0 +1,22 @@
# Pandas
Documento original en inglés: [Pandas](https://github.com/Asabeneh/30-Days-Of-Python/blob/master/25_Day_Pandas/25_pandas.md)
## Ejercicios
1. Lee el archivo hacker_news.csv del directorio de datos.
2. Obtén las primeras cinco filas.
3. Obtén las últimas cinco filas.
4. Obtén la columna de títulos como una serie de pandas.
5. Cuenta el número de filas y columnas.
- Filtra los títulos que contengan "python".
- Filtra los títulos que contengan "JavaScript".
- Explora los datos y dales sentido.
[Solución](01_pandas.py)
[<< Day 24](../24_Estadísticas/README.md) | [Day 26 >>](../26_Desarrollo_web_en_Python/README.md)

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,11 @@
# Desarrollo web en Python
Documento original en inglés: [Python web](https://github.com/Asabeneh/30-Days-Of-Python/blob/master/26_Day_Python_web/26_python_web.md)
## Ejercicios
1. Construirás esta [aplicación](https://thirtydaysofpython-v1-final.herokuapp.com/). Solo queda la parte del analizador de texto.
[Solución](./web/)
[<< Day 25](../25_Pandas/README.md) | [Day 27 >>](../27_Python_con_MongoDB/README.md)

View File

@@ -0,0 +1 @@
web: python app.py

View File

@@ -0,0 +1,44 @@
"""
app.py
"""
from flask import Flask, render_template, request, redirect, url_for
import os
app = Flask(__name__)
app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 0
@app.route('/')
def home():
techs = ['HTML', 'CSS', 'Flask', 'Python']
name = '30 Days Of Python Programming'
return render_template('home.html', techs=techs, name=name, title='Home')
@app.route('/about')
def about():
name = '30 Days Of Python Programming'
return render_template('about.html', name=name, title='About Us')
@app.route('/result')
def result():
return render_template('result.html')
@app.route('/post', methods=['GET', 'POST'])
def post():
name = 'Text Analyzer'
if request.method == 'GET':
return render_template('post.html', name=name, title=name)
if request.method == 'POST':
content = request.form['content']
print(content)
return redirect(url_for('result'))
if __name__ == '__main__':
port = int(os.environ.get("PORT", 5000))
app.run(debug=True, host='0.0.0.0', port=port)

View File

@@ -0,0 +1,7 @@
blinker==1.7.0
click==8.1.7
Flask==3.0.2
itsdangerous==2.1.2
Jinja2==3.1.3
MarkupSafe==2.1.5
Werkzeug==3.0.1

View File

@@ -0,0 +1,206 @@
/* === GENERAL === */
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
/* === css variables === */
:root {
--header-bg-color: #4a7799;
--textarea-bg-color: rgb(250, 246, 246);
--body-bg-color: rgb(210, 214, 210);
--nav-link-color: #bbb;
}
/* === body style === */
body {
background: var(--body-bg-color);
margin: auto;
line-height: 1.75;
font-weight: 900;
word-spacing: 1.5px;
font-family: 'Lato', sans-serif;
font-weight: 300;
}
/* === header style === */
header {
background: var(--header-bg-color);
}
/* === title and subtitle style === */
h1,
h2 {
margin: 20px;
font-weight: 300;
font-family: Nunito;
}
/* === header menu style === */
.menu-container {
width: 90%;
display: flex;
justify-content: space-around;
align-items: center;
color: rgb(221, 215, 215);
padding: 25px;
}
.nav-lists {
display: flex;
}
.nav-list {
list-style: none;
margin: 0 5px;
}
.nav-link {
text-decoration: none;
font-size: 22px;
padding: 0 5px;
color: var(--nav-link-color);
font-weight: 400;
}
.brand-name {
font-size: 28px;
font-weight: bolder;
}
/* === paragraph text style === */
p {
font-size: 22px;
font-weight: 300;
}
/* === main style === */
main {
width: 90%;
margin: auto;
}
/* === container div inside main style === */
.container {
background: rgb(210, 214, 210);
padding: 20px;
margin: auto;
}
.tech-lists {
margin: 10px auto;
text-align: left;
font-size: 20px;
}
.tech {
list-style: none;
}
/* === button style === */
.btn {
width: 150px;
height: 50px;
background: var(--header-bg-color);
color: var(--nav-link-color);
font-size: 20px;
margin: 5px;
border: 1px solid var(--header-bg-color);
font-family: Lato;
cursor: pointer;
}
.btn:focus {
outline: 2px solid #2a70a5;
cursor: pointer;
}
/* === textarea style === */
textarea {
width: 65%;
margin: auto;
padding: 15px;
outline: 2px solid rgba(207, 203, 203, 0.25);
border: none;
font-size: 18px;
font-family: Lato;
font-weight: 300;
}
.result-header {
font-weight: 300;
margin-bottom: 10px;
}
textarea:focus {
border: none;
outline: 2px solid rgba(74, 119, 153, 0.45);
background: var(--textarea-bg-color);
font-size: 18px;
caret-color: var(--header-bg-color);
font-family: Lato;
font-weight: 300;
}
table {
width: 50%;
text-align: center;
border: 1px solid #ccc;
border-collapse: collapse;
}
tr {
background-color: #f8f8f8;
border: 1px solid #ddd;
padding: .35em;
}
tbody tr,
tbody td {
padding: .625em;
text-align: center;
}
thead tr th {
background: var(--header-bg-color);
font-size: .85em;
letter-spacing: .1em;
text-transform: uppercase;
padding: 15px;
color: var(--nav-link-color);
}
/* === responsiveness === */
@media (max-width:600px) {
main {
width: 100%;
}
.menu-container {
flex-direction: column;
justify-content: space-between;
}
h1 {
font-size: 22px;
}
.nav-lists {
flex-direction: column;
}
textarea {
width: 100%;
}
table {
width: 100%;
}
}

View File

@@ -0,0 +1,13 @@
{% extends 'layout.html' %} {% block content %}
<div class="container">
<h1>Sobre esto</h1>
<iframe src="https://giphy.com/embed/eH9sawQbajAQM" width="480" height="120"
frameBorder="0" class="giphy-embed" allowFullScreen></iframe>
<p>
Poco que decir, solo que esto es una web hecha con python y flask.
Es un ejercicio que se ha extraído del <a
href="https://github.com/Asabeneh/30-Days-Of-Python"> repositorio
github de 30DaysOfPython</a>.
</p>
</div>
{% endblock %}

View File

@@ -0,0 +1,23 @@
{% extends 'layout.html' %} {% block content %}
<div class="container">
<h1>Welcome to {{name}}</h1>
<div>
<img src="https://c.tenor.com/Zdpc10JrZrIAAAAC/tenor.gif"
alt="python" />
</div>
<p>
This application clean texts and analyse the number of word, characters
and
most frequent words in the text. Check it out by click text analyzer at
the
menu. You need the following technologies to build this web application:
</p>
<ul class="tech-lists">
{% for tech in techs %}
<li class="tech">{{tech}}</li>
{% endfor %}
</ul>
</div>
{% endblock %}

View File

@@ -0,0 +1,43 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link
href="https://fonts.googleapis.com/css?family=Lato:300,400|Nunito:300,400|Raleway:300,400,500&display=swap"
rel="stylesheet" />
<link
rel="stylesheet"
href="{{ url_for('static', filename='css/main.css') }}" />
{% if title %}
<title>30 Days of Python - {{ title}}</title>
{% else %}
<title>30 Days of Python</title>
{% endif %}
</head>
<body>
<header>
<div class="menu-container">
<div>
<a class="brand-name nav-link" href="/">30DaysOfPython</a>
</div>
<ul class="nav-lists">
<li class="nav-list">
<a class="nav-link active" href="{{ url_for('home') }}">Home</a>
</li>
<li class="nav-list">
<a class="nav-link active" href="{{ url_for('about') }}">About</a>
</li>
<li class="nav-list">
<a class="nav-link active" href="{{ url_for('post') }}">Text
Analyzer</a>
</li>
</ul>
</div>
</header>
<main>
{% block content %} {% endblock %}
</main>
</body>
</html>

View File

@@ -0,0 +1,15 @@
{% extends 'layout.html' %} {% block content %}
<div class="container">
<h1>Text Analyzer</h1>
<form action="localhost:5000/post"
method="POST">
<div>
<textarea rows="25" name="content" autofocus></textarea>
</div>
<div>
<input type="submit" class="btn" value="Process Text" />
</div>
</form>
</div>
{% endblock %}

View File

@@ -0,0 +1,29 @@
"""
Conection
"""
from pymongo.mongo_client import MongoClient
from pymongo.server_api import ServerApi
import os
from dotenv import load_dotenv
load_dotenv()
# variables .env
mongopass = os.getenv('mongopass')
mongouser = os.getenv('mongouser')
mongoname = os.getenv('mongoname')
uri = "mongodb+srv://" + \
mongouser + ":" + \
mongopass + "@" + \
mongoname + ".m697hfm.mongodb.net/?retryWrites=true&w=majority"
# Create a new client and connect to the server
client = MongoClient(uri, server_api=ServerApi('1'))
# Send a ping to confirm a successful connection
try:
client.admin.command('ping')
print("Se envió un ping a su deploy. ¡Se ha conectado correctamente a MongoDB!")
except Exception as e:
print(e)

View File

@@ -0,0 +1,30 @@
"""
Conectar la aplicación flask a la base de datos MongoDB
"""
from pymongo.mongo_client import MongoClient
from pymongo.server_api import ServerApi
from flask import Flask, render_template
import os
from dotenv import load_dotenv
load_dotenv()
# variables .env
mongopass = os.getenv('mongopass')
mongouser = os.getenv('mongouser')
mongoname = os.getenv('mongoname')
uri = "mongodb+srv://" + \
mongouser + ":" + \
mongopass + "@" + \
mongoname + ".m697hfm.mongodb.net/?retryWrites=true&w=majority"
client = MongoClient(uri, server_api=ServerApi('1'))
print(client.list_database_names())
app = Flask(__name__)
if __name__ == '__main__':
port = int(os.environ.get("PORT", 5000))
app.run(debug=True, host='0.0.0.0', port=port)

View File

@@ -0,0 +1,40 @@
"""
Crear una base de datos y una colección
"""
from pymongo.mongo_client import MongoClient
from pymongo.server_api import ServerApi
from flask import Flask, render_template
import os
from dotenv import load_dotenv
load_dotenv()
# variables .env
mongopass = os.getenv('mongopass')
mongouser = os.getenv('mongouser')
mongoname = os.getenv('mongoname')
uri = "mongodb+srv://" + \
mongouser + ":" + \
mongopass + "@" + \
mongoname + ".m697hfm.mongodb.net/?retryWrites=true&w=majority"
client = MongoClient(uri, server_api=ServerApi('1'))
# Creating database
db = client.pruebas_mongodb
# Creating students collection and inserting a document
db.students.insert_one({
'name': 'manuel',
'country': 'Angola',
'city': 'Soria',
'age': 40
})
print(client.list_database_names())
app = Flask(__name__)
if __name__ == '__main__':
port = int(os.environ.get("PORT", 5000))
app.run(debug=True, host='0.0.0.0', port=port)

View File

@@ -0,0 +1,41 @@
"""
Insertar varios documentos en una colección
"""
from pymongo.mongo_client import MongoClient
from pymongo.server_api import ServerApi
from flask import Flask, render_template
import os
from dotenv import load_dotenv
load_dotenv()
# variables .env
mongopass = os.getenv('mongopass')
mongouser = os.getenv('mongouser')
mongoname = os.getenv('mongoname')
uri = "mongodb+srv://" + \
mongouser + ":" + \
mongopass + "@" + \
mongoname + ".m697hfm.mongodb.net/?retryWrites=true&w=majority"
client = MongoClient(uri, server_api=ServerApi('1'))
db = client.pruebas_mongodb
students = [
{'name': 'David', 'country': 'UK', 'city': 'London', 'age': 34},
{'name': 'John', 'country': 'Sweden', 'city': 'Stockholm', 'age': 28},
{'name': 'Sami', 'country': 'Finland', 'city': 'Helsinki', 'age': 25},
]
for student in students:
db.students.insert_one(student)
app = Flask(__name__)
if __name__ == '__main__':
# for deployment we use the environ
# to make it work for both production and development
port = int(os.environ.get("PORT", 5000))
app.run(debug=True, host='0.0.0.0', port=port)

View File

@@ -0,0 +1,55 @@
"""
Buscar en la base de datos
"""
from pymongo.mongo_client import MongoClient
from pymongo.server_api import ServerApi
from flask import Flask, render_template
import os
from dotenv import load_dotenv
from bson.objectid import ObjectId
load_dotenv()
# variables .env
mongopass = os.getenv('mongopass')
mongouser = os.getenv('mongouser')
mongoname = os.getenv('mongoname')
uri = "mongodb+srv://" + \
mongouser + ":" + \
mongopass + "@" + \
mongoname + ".m697hfm.mongodb.net/?retryWrites=true&w=majority"
client = MongoClient(uri, server_api=ServerApi('1'))
db = client.pruebas_mongodb
student = db.students.find_one({'name': 'David'})
print(student)
print("-"*30)
student_two = db.students.find_one(
{'_id': ObjectId('652472bfccdbb81a3f7473e5')})
print(student_two)
print("-"*30)
students = db.students.find()
for student in students:
print(student)
print("-"*30)
students = db.students.find({}, {"_id": 0, "name": 1, "country": 1})
for student in students:
print(student)
print("-"*30)
app = Flask(__name__)
if __name__ == '__main__':
# for deployment we use the environ
# to make it work for both production and development
port = int(os.environ.get("PORT", 5000))
app.run(debug=True, host='0.0.0.0', port=port)

View File

@@ -0,0 +1,70 @@
"""
Buscar en la base de datos con query
"""
from pymongo.mongo_client import MongoClient
from pymongo.server_api import ServerApi
from flask import Flask, render_template
import os
from dotenv import load_dotenv
from bson.objectid import ObjectId
load_dotenv()
# variables .env
mongopass = os.getenv('mongopass')
mongouser = os.getenv('mongouser')
mongoname = os.getenv('mongoname')
uri = "mongodb+srv://" + \
mongouser + ":" + \
mongopass + "@" + \
mongoname + ".m697hfm.mongodb.net/?retryWrites=true&w=majority"
client = MongoClient(uri, server_api=ServerApi('1'))
db = client.pruebas_mongodb
query = {
"country": "Finland"
}
students = db.students.find(query)
for student in students:
print(student)
print("-"*30)
query = {
"city": "Helsinki"
}
students = db.students.find(query)
for student in students:
print(student)
print("-"*30)
query = {
"country": "Finland",
"city": "Helsinki"
}
students = db.students.find(query)
for student in students:
print(student)
print("-"*30)
query = {"age": {"$gt": 30}}
students = db.students.find(query)
for student in students:
print(student)
app = Flask(__name__)
if __name__ == '__main__':
# for deployment we use the environ
# to make it work for both production and development
port = int(os.environ.get("PORT", 5000))
app.run(debug=True, host='0.0.0.0', port=port)

View File

@@ -0,0 +1,71 @@
"""
Buscar en la base de datos - más opciones
"""
from pymongo.mongo_client import MongoClient
from pymongo.server_api import ServerApi
from flask import Flask, render_template
import os
from dotenv import load_dotenv
from bson.objectid import ObjectId
load_dotenv()
# variables .env
mongopass = os.getenv('mongopass')
mongouser = os.getenv('mongouser')
mongoname = os.getenv('mongoname')
uri = "mongodb+srv://" + \
mongouser + ":" + \
mongopass + "@" + \
mongoname + ".m697hfm.mongodb.net/?retryWrites=true&w=majority"
client = MongoClient(uri, server_api=ServerApi('1'))
db = client.pruebas_mongodb
db.students.find().limit(3)
print("-"*30)
students = db.students.find().sort('name')
for student in students:
print(student)
print("-"*30)
students = db.students.find().sort('name', -1)
for student in students:
print(student)
print("-"*30)
students = db.students.find().sort('age')
for student in students:
print(student)
print("-"*30)
students = db.students.find().sort('age', -1)
for student in students:
print(student)
print("-"*30)
# New value
query = {'age': 40}
new_value = {'$set': {'age': 38}}
db.students.update_one(query, new_value)
# lets check the result if the age is modified
for student in db.students.find():
print(student)
app = Flask(__name__)
if __name__ == '__main__':
# for deployment we use the environ
# to make it work for both production and development
port = int(os.environ.get("PORT", 5000))
app.run(debug=True, host='0.0.0.0', port=port)

View File

@@ -0,0 +1,46 @@
"""
Buscar en la base de datos con query
"""
from pymongo.mongo_client import MongoClient
from pymongo.server_api import ServerApi
from flask import Flask, render_template
import os
from dotenv import load_dotenv
from bson.objectid import ObjectId
load_dotenv()
# variables .env
mongopass = os.getenv('mongopass')
mongouser = os.getenv('mongouser')
mongoname = os.getenv('mongoname')
uri = "mongodb+srv://" + \
mongouser + ":" + \
mongopass + "@" + \
mongoname + ".m697hfm.mongodb.net/?retryWrites=true&w=majority"
client = MongoClient(uri, server_api=ServerApi('1'))
db = client.pruebas_mongodb
# Delete one document
query = {'name': 'John'}
db.students.delete_one(query)
# Delete many documents
for student in db.students.find():
print(student)
for student in db.students.find():
print(student)
# Drop collection
db.students.drop()
app = Flask(__name__)
if __name__ == '__main__':
# for deployment we use the environ
# to make it work for both production and development
port = int(os.environ.get("PORT", 5000))
app.run(debug=True, host='0.0.0.0', port=port)

Some files were not shown because too many files have changed in this diff Show More