Skip to content

Commit 640d776

Browse files
authored
Merge pull request #6802 from Maanghel/main
#9 - Python
2 parents f8f389e + b88350f commit 640d776

File tree

2 files changed

+158
-0
lines changed
  • Retos
    • Reto #10 - LA API [Media]/python
    • Reto #9 - HETEROGRAMA, ISOGRAMA Y PANGRAMA [Fácil]/python

2 files changed

+158
-0
lines changed
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
"""
2+
Llamar a una API es una de las tareas más comunes en programación.
3+
4+
Implementa una llamada HTTP a una API (la que tú quieras) y muestra su
5+
resultado a través de la terminal. Por ejemplo: Pokémon, Marvel...
6+
7+
Aquí tienes un listado de posibles APIs:
8+
https://github.com/public-apis/public-apis
9+
"""
10+
11+
from typing import List, Dict
12+
import requests
13+
14+
URL: str = "https://digimon-api.vercel.app/api/digimon"
15+
16+
def fetch_digimons(url: str) -> List[Dict[str, str]]:
17+
"""
18+
Fetch Digimon data from the given API URL.
19+
20+
Args:
21+
url (str): API endpoint.
22+
23+
Returns:
24+
List[Dict[str, str]]: List of digimons with their attributes.
25+
26+
Raises:
27+
requests.RequestException: If there is a network or HTTP error.
28+
ValueError: If data is not a list.
29+
"""
30+
try:
31+
response = requests.get(url, timeout=5)
32+
response.raise_for_status()
33+
data = response.json()
34+
35+
if not isinstance(data, list):
36+
raise ValueError("Formato de respuesta de la API inesperado.")
37+
38+
return data
39+
except (requests.RequestException, ValueError) as e:
40+
print(f"Error obteniendo datos: {e}")
41+
return []
42+
43+
def display_digimons(digimons: List[Dict[str, str]]) -> None:
44+
"""
45+
Print digimon names and levels to the console.
46+
47+
Args:
48+
digimons (List[Dict[str, str]]): List of digimons to display.
49+
"""
50+
for index, digimon in enumerate(digimons, 1):
51+
name = digimon.get("name", "Unknown")
52+
level = digimon.get("level", "Unknown")
53+
print(f"\nIndex: {index}\nNombre: {name}\nNivel: {level}")
54+
55+
56+
if __name__ == "__main__":
57+
digimons = fetch_digimons(URL)
58+
display_digimons(digimons)
Lines changed: 100 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,100 @@
1+
"""
2+
Crea 3 funciones, cada una encargada de detectar si una cadena de
3+
texto es un heterograma, un isograma o un pangrama.
4+
- Debes buscar la definición de cada uno de estos términos.
5+
"""
6+
7+
from typing import Dict, Set
8+
9+
def is_pangram(text: str) -> bool:
10+
"""
11+
Check if a given text is a pangram.
12+
13+
A pangram is a sentence that contains every letter of the alphabet at least once.
14+
15+
Args:
16+
text (str): The input text to evaluate.
17+
18+
Returns:
19+
bool: True if the text is a pangram, False otherwise.
20+
"""
21+
_validate(text)
22+
text = text.lower()
23+
alphabet: Set[str] = set("abcdefghijklmnopqrstuvwxyz")
24+
letters: Set[str] = {char for char in text if char.isalpha()}
25+
return letters >= alphabet
26+
27+
def is_heterogram(text: str) -> bool:
28+
"""
29+
Check if a given text is a heterogram.
30+
31+
A heterogram is a word or sentence in which no letter is repeated.
32+
33+
Args:
34+
text (str): The input text to evaluate.
35+
36+
Returns:
37+
bool: True if the text is a heterogram, False otherwise.
38+
"""
39+
_validate(text)
40+
text = text.lower()
41+
seen_letters: Set[str] = set()
42+
for char in text:
43+
if char.isalpha():
44+
if char in seen_letters:
45+
return False
46+
seen_letters.add(char)
47+
return True
48+
49+
def is_isogram(text: str) -> bool:
50+
"""
51+
Check if a given text is an isogram.
52+
53+
An isogram is a word or sentence where each letter occurs the same number of times.
54+
55+
Args:
56+
text (str): The input text to evaluate.
57+
58+
Returns:
59+
bool: True if the text is an isogram, False otherwise.
60+
"""
61+
_validate(text)
62+
text = text.lower()
63+
letters_count: Dict[str, int] = {}
64+
for char in text:
65+
if char.isalpha():
66+
if char in letters_count:
67+
letters_count[char] += 1
68+
else:
69+
letters_count[char] = 1
70+
return len(set(letters_count.values())) == 1
71+
72+
def _validate(data: str) -> None:
73+
"""
74+
Validate the input data to ensure it is a non-empty string.
75+
76+
Args:
77+
data (str): The input to validate.
78+
79+
Raises:
80+
TypeError: If the input is not a string.
81+
ValueError: If the string is empty.
82+
"""
83+
if not isinstance(data, str):
84+
raise TypeError("Solo se aceptan cadenas de textos.")
85+
if not data:
86+
raise ValueError("Las cadenas de textos no pueden estar vacias.")
87+
88+
if __name__ == "__main__":
89+
test_texts = [
90+
"Un jugoso zumo de piña y kiwi bien frio es exquisito y no lleva alcohol", # Pangrama
91+
"Logica", # Isograma
92+
"Adultero" # Heterograma
93+
]
94+
95+
for text in test_texts:
96+
print(f"Texto: '{text}'")
97+
print(f"Es pangrama: {is_pangram(text)}")
98+
print(f"Es heterograma: {is_heterogram(text)}")
99+
print(f"Es isograma: {is_isogram(text)}")
100+
print()

0 commit comments

Comments
 (0)