Skip to content

Commit 6274f55

Browse files
committed
feat: add articles to easy challenges
1 parent 804935e commit 6274f55

File tree

10 files changed

+630
-0
lines changed

10 files changed

+630
-0
lines changed
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
# Challenge Description and Solution
2+
3+
## English Version
4+
5+
### Challenge Description
6+
Given a string, create a function that reverses it without using built-in reverse methods. This challenge helps you practice loops and index handling in Python.
7+
8+
### Code Explanation
9+
The function `reverse_string` takes a string `s` as input and creates a new string `reversed_str` containing the characters of `s` in reverse order. It uses a `for` loop that iterates from the last character to the first, appending each character to `reversed_str`. Finally, the function returns the reversed string.
10+
11+
Relevant code:
12+
13+
```python
14+
def reverse_string(s):
15+
reversed_str = ""
16+
for i in range(len(s) - 1, -1, -1):
17+
reversed_str += s[i]
18+
return reversed_str
19+
```
20+
21+
The `if __name__ == "__main__":` block contains an example usage where the string `"hello"` is reversed and the result is printed.
22+
23+
```python
24+
if __name__ == "__main__":
25+
test_string = "hello"
26+
print("Original string:", test_string)
27+
print("Reversed string:", reverse_string(test_string))
28+
```
29+
30+
## Versión en Español
31+
32+
### Descripción del Reto
33+
Dada una cadena de caracteres, crea una función que la invierta sin usar métodos integrados de inversión. Este reto te ayudará a practicar el uso de bucles y el manejo de índices en Python.
34+
35+
### Explicación del Código
36+
La función `reverse_string` toma una cadena `s` como entrada y crea una nueva cadena `reversed_str` que contiene los caracteres de `s` en orden inverso. Para ello, se utiliza un bucle `for` que recorre la cadena desde el último carácter hasta el primero, agregando cada carácter a `reversed_str`. Finalmente, la función retorna la cadena invertida.
37+
38+
Código relevante:
39+
40+
```python
41+
def reverse_string(s):
42+
reversed_str = ""
43+
for i in range(len(s) - 1, -1, -1):
44+
reversed_str += s[i]
45+
return reversed_str
46+
```
47+
48+
El bloque `if __name__ == "__main__":` contiene un ejemplo de uso donde se invierte la cadena `"hello"` y se imprime el resultado.
49+
50+
```python
51+
if __name__ == "__main__":
52+
test_string = "hello"
53+
print("Cadena original:", test_string)
54+
print("Cadena invertida:", reverse_string(test_string))
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
# Challenge Description and Solution
2+
3+
## English Version
4+
5+
### Challenge Description
6+
Write a function that determines if a number is even or odd. Test with different types of inputs (positive numbers, negative numbers, and zero) to ensure robustness.
7+
8+
### Code Explanation
9+
The `is_even` function uses the modulo operator `%` to determine if a number is even. If the remainder of the division of the number by 2 is zero, the number is even; otherwise, it is odd.
10+
11+
Relevant code:
12+
13+
```python
14+
def is_even(n):
15+
return n % 2 == 0
16+
```
17+
18+
The `if __name__ == "__main__":` block contains an example usage that tests several values and prints whether they are even or odd.
19+
20+
```python
21+
if __name__ == "__main__":
22+
test_values = [0, 1, -1, 2, -2, 15, -15]
23+
for val in test_values:
24+
result = "even" if is_even(val) else "odd"
25+
print(f"{val} is {result}")
26+
```
27+
28+
## Versión en Español
29+
30+
### Descripción del Reto
31+
Escribe una función que determine si un número es par o impar. Prueba con diferentes tipos de entradas (números positivos, negativos y cero) para asegurar la robustez.
32+
33+
### Explicación del Código
34+
La función `is_even` utiliza el operador módulo `%` para determinar si un número es par. Si el residuo de la división entre el número y 2 es cero, el número es par; de lo contrario, es impar.
35+
36+
Código relevante:
37+
38+
```python
39+
def is_even(n):
40+
return n % 2 == 0
41+
```
42+
43+
El bloque `if __name__ == "__main__":` contiene un ejemplo de uso que prueba varios valores y muestra si son pares o impares.
44+
45+
```python
46+
if __name__ == "__main__":
47+
test_values = [0, 1, -1, 2, -2, 15, -15]
48+
for val in test_values:
49+
result = "even" if is_even(val) else "odd"
50+
print(f"{val} is {result}")
Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
# Challenge Description and Solution
2+
3+
## English Version
4+
5+
### Challenge Description
6+
Implement a function that determines if a number is prime. Pay attention to edge cases such as negative values and the number 1.
7+
8+
### Code Explanation
9+
The `is_prime` function checks if a number `n` is prime. It first excludes numbers less than or equal to 1, which are not prime. Then, it considers 2 and 3 as prime numbers. Next, it eliminates multiples of 2 and 3. Finally, it uses a loop that checks divisors starting from 5, skipping multiples of 6, to optimize the search. If a divisor is found, it returns `False`; otherwise, it returns `True`.
10+
11+
Relevant code:
12+
13+
```python
14+
def is_prime(n):
15+
if n <= 1:
16+
return False
17+
if n <= 3:
18+
return True
19+
if n % 2 == 0 or n % 3 == 0:
20+
return False
21+
i = 5
22+
while i * i <= n:
23+
if n % i == 0 or n % (i + 2) == 0:
24+
return False
25+
i += 6
26+
return True
27+
```
28+
29+
The `if __name__ == "__main__":` block contains an example usage that tests several numbers and prints whether they are prime or not.
30+
31+
```python
32+
if __name__ == "__main__":
33+
test_numbers = [-1, 0, 1, 2, 3, 4, 5, 29, 35]
34+
for num in test_numbers:
35+
print(f"{num} is prime: {is_prime(num)}")
36+
```
37+
38+
## Versión en Español
39+
40+
### Descripción del Reto
41+
Implementa una función que determine si un número es primo. Presta atención a casos especiales como valores negativos y el número 1.
42+
43+
### Explicación del Código
44+
La función `is_prime` verifica si un número `n` es primo. Primero descarta números menores o iguales a 1, que no son primos. Luego, considera los números 2 y 3 como primos. Después, elimina múltiplos de 2 y 3. Finalmente, utiliza un bucle que verifica divisores desde 5 en adelante, saltando múltiplos de 6, para optimizar la búsqueda. Si encuentra un divisor, retorna `False`; si no, retorna `True`.
45+
46+
Código relevante:
47+
48+
```python
49+
def is_prime(n):
50+
if n <= 1:
51+
return False
52+
if n <= 3:
53+
return True
54+
if n % 2 == 0 or n % 3 == 0:
55+
return False
56+
i = 5
57+
while i * i <= n:
58+
if n % i == 0 or n % (i + 2) == 0:
59+
return False
60+
i += 6
61+
return True
62+
```
63+
64+
El bloque `if __name__ == "__main__":` contiene un ejemplo de uso que prueba varios números y muestra si son primos o no.
65+
66+
```python
67+
if __name__ == "__main__":
68+
test_numbers = [-1, 0, 1, 2, 3, 4, 5, 29, 35]
69+
for num in test_numbers:
70+
print(f"{num} is prime: {is_prime(num)}")
Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
# Challenge Description and Solution
2+
3+
## English Version
4+
5+
### Challenge Description
6+
Create a generator that returns the Fibonacci sequence up to n terms. You can explore iterative and recursive approaches to solve the problem.
7+
8+
### Code Explanation
9+
The code presents two generator functions for the Fibonacci sequence:
10+
11+
- `fibonacci_iterative(n)`: Uses a `for` loop to generate the first n terms of the Fibonacci sequence iteratively. It initializes two variables `a` and `b` with 0 and 1 respectively, and in each iteration yields the current value of `a` and updates `a` and `b`.
12+
13+
- `fibonacci_recursive(n, a=0, b=1)`: Generates the Fibonacci sequence recursively. If `n` is 0, it ends the recursion. Otherwise, it yields the current value `a` and recursively calls itself with `n-1`, `b`, and `a+b`.
14+
15+
Relevant code:
16+
17+
```python
18+
def fibonacci_iterative(n):
19+
a, b = 0, 1
20+
for _ in range(n):
21+
yield a
22+
a, b = b, a + b
23+
24+
def fibonacci_recursive(n, a=0, b=1):
25+
if n == 0:
26+
return
27+
yield a
28+
yield from fibonacci_recursive(n-1, b, a + b)
29+
```
30+
31+
The `if __name__ == "__main__":` block shows an example usage that prints the Fibonacci sequence generated by both methods for n=10.
32+
33+
```python
34+
if __name__ == "__main__":
35+
n = 10
36+
print("Iterative Fibonacci sequence:")
37+
for num in fibonacci_iterative(n):
38+
print(num, end=" ")
39+
print("\nRecursive Fibonacci sequence:")
40+
for num in fibonacci_recursive(n):
41+
print(num, end=" ")
42+
print()
43+
```
44+
45+
## Versión en Español
46+
47+
### Descripción del Reto
48+
Crea un generador que devuelva la secuencia de Fibonacci hasta n términos. Puedes explorar enfoques iterativos y recursivos para resolver el problema.
49+
50+
### Explicación del Código
51+
El código presenta dos funciones generadoras para la secuencia de Fibonacci:
52+
53+
- `fibonacci_iterative(n)`: Utiliza un bucle `for` para generar los primeros n términos de la secuencia de Fibonacci de manera iterativa. Inicializa dos variables `a` y `b` con 0 y 1 respectivamente, y en cada iteración produce el valor actual de `a` y actualiza `a` y `b`.
54+
55+
- `fibonacci_recursive(n, a=0, b=1)`: Genera la secuencia de Fibonacci de forma recursiva. Si `n` es 0, termina la recursión. De lo contrario, produce el valor actual `a` y llama recursivamente a sí misma con `n-1`, `b` y `a+b`.
56+
57+
Código relevante:
58+
59+
```python
60+
def fibonacci_iterative(n):
61+
a, b = 0, 1
62+
for _ in range(n):
63+
yield a
64+
a, b = b, a + b
65+
66+
def fibonacci_recursive(n, a=0, b=1):
67+
if n == 0:
68+
return
69+
yield a
70+
yield from fibonacci_recursive(n-1, b, a + b)
71+
```
72+
73+
El bloque `if __name__ == "__main__":` muestra un ejemplo de uso que imprime la secuencia de Fibonacci generada por ambos métodos para n=10.
74+
75+
```python
76+
if __name__ == "__main__":
77+
n = 10
78+
print("Iterative Fibonacci sequence:")
79+
for num in fibonacci_iterative(n):
80+
print(num, end=" ")
81+
print("\nRecursive Fibonacci sequence:")
82+
for num in fibonacci_recursive(n):
83+
print(num, end=" ")
84+
print()
Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
# Challenge Description and Solution
2+
3+
## English Version
4+
5+
### Challenge Description
6+
Develop a recursive or iterative function to calculate the factorial of a non-negative integer. Consider handling special cases.
7+
8+
### Code Explanation
9+
The code presents two functions to calculate the factorial:
10+
11+
- `factorial_recursive(n)`: Calculates the factorial recursively. If `n` is negative, it raises an error. If `n` is 0 or 1, it returns 1. Otherwise, it returns `n` multiplied by the factorial of `n-1`.
12+
13+
- `factorial_iterative(n)`: Calculates the factorial iteratively. If `n` is negative, it raises an error. It initializes `result` to 1 and successively multiplies by each number from 2 to `n`.
14+
15+
Relevant code:
16+
17+
```python
18+
def factorial_recursive(n):
19+
if n < 0:
20+
raise ValueError("Factorial is not defined for negative numbers")
21+
if n == 0 or n == 1:
22+
return 1
23+
return n * factorial_recursive(n - 1)
24+
25+
def factorial_iterative(n):
26+
if n < 0:
27+
raise ValueError("Factorial is not defined for negative numbers")
28+
result = 1
29+
for i in range(2, n + 1):
30+
result *= i
31+
return result
32+
```
33+
34+
The `if __name__ == "__main__":` block contains an example usage that calculates the factorial of several values using both methods.
35+
36+
```python
37+
if __name__ == "__main__":
38+
test_values = [0, 1, 5, 7]
39+
for val in test_values:
40+
print(f"Factorial of {val} (recursive): {factorial_recursive(val)}")
41+
print(f"Factorial of {val} (iterative): {factorial_iterative(val)}")
42+
```
43+
44+
## Versión en Español
45+
46+
### Descripción del Reto
47+
Desarrolla una función recursiva o iterativa para calcular el factorial de un número entero no negativo. Considera el manejo de casos especiales como números negativos.
48+
49+
### Explicación del Código
50+
El código presenta dos funciones para calcular el factorial:
51+
52+
- `factorial_recursive(n)`: Calcula el factorial de forma recursiva. Si `n` es negativo, lanza un error. Si `n` es 0 o 1, retorna 1. En otro caso, retorna `n` multiplicado por el factorial de `n-1`.
53+
54+
- `factorial_iterative(n)`: Calcula el factorial de forma iterativa. Si `n` es negativo, lanza un error. Inicializa `result` en 1 y multiplica sucesivamente por cada número desde 2 hasta `n`.
55+
56+
Código relevante:
57+
58+
```python
59+
def factorial_recursive(n):
60+
if n < 0:
61+
raise ValueError("Factorial is not defined for negative numbers")
62+
if n == 0 or n == 1:
63+
return 1
64+
return n * factorial_recursive(n - 1)
65+
66+
def factorial_iterative(n):
67+
if n < 0:
68+
raise ValueError("Factorial is not defined for negative numbers")
69+
result = 1
70+
for i in range(2, n + 1):
71+
result *= i
72+
return result
73+
```
74+
75+
El bloque `if __name__ == "__main__":` contiene un ejemplo de uso que calcula el factorial de varios valores usando ambos métodos.
76+
77+
```python
78+
if __name__ == "__main__":
79+
test_values = [0, 1, 5, 7]
80+
for val in test_values:
81+
print(f"Factorial of {val} (recursive): {factorial_recursive(val)}")
82+
print(f"Factorial of {val} (iterative): {factorial_iterative(val)}")

0 commit comments

Comments
 (0)