Skip to content

Commit 852da8b

Browse files
committed
#14 - Python
1 parent 9db27e4 commit 852da8b

File tree

1 file changed

+85
-0
lines changed
  • Retos/Reto #14 - OCTAL Y HEXADECIMAL [Fácil]/python

1 file changed

+85
-0
lines changed
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)