Skip to content

Commit 6944d53

Browse files
authored
Merge pull request #6804 from Maanghel/main
#13/14 - Python
2 parents b771cd2 + 175a61d commit 6944d53

File tree

3 files changed

+250
-0
lines changed
  • Retos

3 files changed

+250
-0
lines changed
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
"""
2+
Crea una función que sea capaz de detectar si existe un viernes 13
3+
en el mes y el año indicados.
4+
- La función recibirá el mes y el año y retornará verdadero o falso.
5+
"""
6+
7+
from datetime import date
8+
9+
def have_friday_13(year: int, month: int) -> bool:
10+
"""Check if the 13th of a given month/year falls on a Friday.
11+
12+
Args:
13+
year (int): Year to check.
14+
month (int): Month to check (1-12).
15+
16+
Returns:
17+
bool: True if the 13th is Friday, False otherwise.
18+
19+
Raises:
20+
TypeError: If arguments are not integers.
21+
ValueError: If month is not in 1-12.
22+
"""
23+
if not isinstance(year, int) or not isinstance(month, int):
24+
raise TypeError("El año y el mes deben ser enteros.")
25+
if not 1 <= month <= 12:
26+
raise ValueError("El mes debe estar entre 1 y 12.")
27+
28+
return date(year, month, 13).weekday() == 4
29+
30+
31+
if __name__ == "__main__":
32+
print(have_friday_13(1900, 5)) # False
33+
print(have_friday_13(2023, 10)) # True
Lines changed: 132 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,132 @@
1+
"""
2+
Crea un pequeño juego que consista en adivinar palabras en un número máximo de intentos:
3+
- El juego comienza proponiendo una palabra aleatoria incompleta
4+
- Por ejemplo "m_ur_d_v", y el número de intentos que le quedan
5+
- El usuario puede introducir únicamente una letra o una palabra (de la misma longitud que
6+
la palabra a adivinar)
7+
- Si escribe una letra y acierta, se muestra esa letra en la palabra. Si falla, se resta
8+
uno al número de intentos
9+
- Si escribe una resolución y acierta, finaliza el juego, en caso contrario, se resta uno
10+
al número de intentos
11+
- Si el contador de intentos llega a 0, el jugador pierde
12+
- La palabra debe ocultar de forma aleatoria letras, y nunca puede comenzar
13+
ocultando más del 60%
14+
- Puedes utilizar las palabras que quieras y el número de intentos que consideres
15+
"""
16+
17+
import random
18+
19+
class Game:
20+
"""
21+
A simple word guessing game where the player has to guess
22+
a randomly chosen word by suggesting letters or the full word.
23+
24+
Attributes:
25+
words (list[str]): List of possible words for the game.
26+
replace_probabilities (float): Maximum percentage of letters that can be hidden.
27+
max_attempts (int): Maximum number of attempts allowed.
28+
random_word (str): The randomly chosen word for the game.
29+
current_lyrics (list[str]): The current state of the word with hidden/revealed letters.
30+
attempts_left (int): Number of attempts the player has left.
31+
"""
32+
33+
words = [
34+
"murcielago", "python", "programacion", "desarrollo", "reto", "palabra", "adivina", "juego",
35+
"computadora", "teclado", "raton", "pantalla", "internet", "variable", "funcion", "bucle",
36+
"condicional", "lista", "diccionario", "conjunto", "tupla"
37+
]
38+
replace_probabilities = 0.6
39+
40+
def __init__(self, max_attempts: int = 6) -> None:
41+
"""
42+
Initialize the game with a random word and hidden letters.
43+
44+
Args:
45+
max_attempts (int): Maximum number of attempts allowed. Default is 6.
46+
"""
47+
self.max_attempts = max_attempts
48+
self.random_word = random.choice(self.words)
49+
self.current_lyrics = self._generate_incomplete_word()
50+
self.attempts_left = self.max_attempts
51+
52+
def _generate_incomplete_word(self) -> list[str]:
53+
"""
54+
Generate the word with randomly hidden letters, ensuring no more
55+
than 60% of the word is hidden.
56+
57+
Returns:
58+
list[str]: The word represented as a list with some letters replaced by '_'.
59+
"""
60+
max_hidden = int(len(self.random_word) * self.replace_probabilities)
61+
num_letters_to_hide = random.randint(1, max_hidden)
62+
hidden_positions = random.sample(range(len(self.random_word)), num_letters_to_hide)
63+
64+
return [
65+
"_" if i in hidden_positions else char
66+
for i, char in enumerate(self.random_word)
67+
]
68+
69+
def main(self) -> None:
70+
"""
71+
Run the main game loop until the player wins or runs out of attempts.
72+
"""
73+
while self.attempts_left > 0:
74+
self._display_round()
75+
user_input = input("Ingresa una letra o la palabra completa: ").lower()
76+
77+
if len(user_input) == 1 and user_input.isalpha():
78+
self._guess_letter(user_input)
79+
elif len(user_input) == len(self.random_word):
80+
self._guess_word(user_input)
81+
else:
82+
print("Entrada invalida. Intente de nuevo.")
83+
84+
if "_" not in self.current_lyrics:
85+
print(f"Felicidades!! Completaste la palabra: {self.random_word}")
86+
return
87+
88+
print(f"Te quedaste sin intentos! La palabra era: '{self.random_word}'.")
89+
90+
def _guess_letter(self, letter: str) -> None:
91+
"""
92+
Check if the guessed letter is in the word.
93+
94+
Args:
95+
letter (str): The guessed letter.
96+
"""
97+
if letter in self.random_word:
98+
for i, char in enumerate(self.random_word):
99+
if char == letter:
100+
self.current_lyrics[i] = letter
101+
print(f"Correcto! La palabra ahora es: {''.join(self.current_lyrics)}")
102+
else:
103+
self.attempts_left -= 1
104+
print(f"Respuesta incorrecta. Intentos restantes: {self.attempts_left}")
105+
106+
def _guess_word(self, word: str) -> None:
107+
"""
108+
Check if the guessed word matches the random word.
109+
110+
Args:
111+
word (str): The guessed word.
112+
"""
113+
if word == self.random_word:
114+
print(f"Ganaste! La palabra es: '{self.random_word}'.")
115+
self.current_lyrics = list(self.random_word)
116+
return
117+
else:
118+
self.attempts_left -= 1
119+
print(f"Respuesta incorrecta. Intentos restantes: {self.attempts_left}")
120+
121+
def _display_round(self) -> None:
122+
"""
123+
Display the current round number, attempts left, and the incomplete word.
124+
"""
125+
print(f"\nRonda: {(self.max_attempts - self.attempts_left) + 1} de {self.max_attempts}")
126+
print(f"Palabra incompleta: {''.join(self.current_lyrics)}")
127+
print("-" * 50)
128+
129+
130+
if __name__ == "__main__":
131+
game = Game()
132+
game.main()
Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
"""
2+
Crea una función que reciba un número decimal y lo trasforme a Octal
3+
y Hexadecimal.
4+
- No está permitido usar funciones propias del lenguaje de programación que
5+
realicen esas operaciones directamente.
6+
"""
7+
8+
def _validate_data(decimal: int) -> None:
9+
"""
10+
Validate the input data for conversion.
11+
12+
Ensures the value is a positive integer greater than zero.
13+
Raises an appropriate exception if the input is invalid.
14+
15+
Args:
16+
decimal (int): The number to validate.
17+
18+
Raises:
19+
TypeError: If the input is not an integer.
20+
ValueError: If the input is zero or a negative integer.
21+
"""
22+
if not isinstance(decimal, int):
23+
raise TypeError("Solo se admiten enteros positivos como datos.")
24+
if not decimal:
25+
raise ValueError("tiene que ingresar un valor positivo.")
26+
if decimal < 0:
27+
raise ValueError("Solo se admiten enteros positivos como datos.")
28+
29+
def _to_base(decimal: int, base: int) -> str:
30+
"""
31+
Convert a decimal integer into a string representation in the specified base.
32+
33+
This function uses successive integer division and remainders to transform
34+
a decimal number into another base (e.g., binary, octal, hexadecimal).
35+
It supports bases up to 16, using digits 0/9 and letters A/F for values >= 10.
36+
37+
Args:
38+
decimal (int): The number in decimal format to be converted.
39+
base (int): The target base (e.g., 2 for binary, 8 for octal, 16 for hex).
40+
41+
Returns:
42+
str: The string representation of the number in the target base.
43+
"""
44+
symbols = "0123456789ABCDEF"
45+
digits = []
46+
47+
if decimal == 0:
48+
return "0"
49+
50+
while decimal > 0:
51+
remainder = decimal % base
52+
digits.append(symbols[remainder])
53+
decimal //= base
54+
55+
return ''.join(reversed(digits))
56+
57+
def to_octal_and_hex(decimal: int) -> str:
58+
"""
59+
Convert a decimal number into its Octal and Hexadecimal string representations.
60+
61+
This function internally calls `to_base` with base 8 (Octal) and base 16 (Hexadecimal).
62+
It avoids using Python's built-in conversion functions such as `oct()` or `hex()`.
63+
64+
Args:
65+
decimal (int): The number in decimal format to be converted.
66+
67+
Returns:
68+
str: A descriptive message containing the decimal number and its octal
69+
and hexadecimal equivalents.
70+
"""
71+
try:
72+
_validate_data(decimal)
73+
except (ValueError, TypeError) as e:
74+
return f"Error: {e}"
75+
76+
octal = _to_base(decimal, 8)
77+
hexa = _to_base(decimal, 16)
78+
79+
return f"El número {decimal} en octal es {octal} y en hexadecimal es {hexa}"
80+
81+
82+
if __name__ == "__main__":
83+
print(to_octal_and_hex(1))
84+
print(to_octal_and_hex(255))
85+
print(to_octal_and_hex(-1))

0 commit comments

Comments
 (0)