Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 26 additions & 1 deletion exercises/binary_search_recursive/solution.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,26 @@ def binary_search_recursive(
lst: list[int], target: int, low: int = 0, high: int | None = None
) -> int:
"""Recursive Binary Search"""
pass

if high is None:
high = len(lst) - 1 # inicializar variable

if not lst[low] <= target <= lst[high]:
return -1 # 4. no encontrado

# 1. cortar a la mitad la lista
mid = (low + high)//2 # calculando la mitad

# 2. el valor del medio compararlo con el target y tomar desiciones sobre descartar las sublistas
if lst[mid] == target:
return mid # 3. se encontro, retornar el indice
elif lst[mid] > target:
lst[0:mid]
return binary_search_recursive(lst, target, low, mid - 1)
elif lst[mid] < target:
lst[mid + 1:]
return binary_search_recursive(lst, target, mid + 1, len(lst) - 1)



def test() -> None:
Expand All @@ -16,6 +35,12 @@ def test() -> None:
assert binary_search_recursive([1, 2, 3, 4, 5], 6) == -1, (
f"Expected -1, got {binary_search_recursive([1, 2, 3, 4, 5], 6)}"
)
assert binary_search_recursive([1, 2, 3, 4, 5], 5) == 4, (
f"Expected 4, got {binary_search_recursive([1, 2, 3, 4, 5], 4)}"
)
assert binary_search_recursive([1, 2, 3, 4, 5], 1) == 0, (
f"Expected 0, got {binary_search_recursive([1, 2, 3, 4, 5], 1)}"
)
print("✅ All tests passed!")


Expand Down
34 changes: 23 additions & 11 deletions exercises/case_inverter/solution.py
Original file line number Diff line number Diff line change
@@ -1,28 +1,40 @@
SUBMIT = False

def case_inverter_rec(s: str, inverted_s: str, index: int):

if len(s) == len(inverted_s):
return inverted_s

current_char = s[index]
if not current_char.isalpha():
inverted_s += current_char
return case_inverter_rec(s, inverted_s, index + 1)
elif current_char.islower():
inverted_s += current_char.upper()
return case_inverter_rec(s, inverted_s, index + 1)
else:
inverted_s += current_char.lower()
return case_inverter_rec(s, inverted_s, index + 1)


def case_inverter(s: str) -> str: # noqa: ARG001
"""
Inverts the case of each character in a string.
"""
inverted_s = ""
for char in s:
if char.islower():
inverted_s += char.upper()
elif char.isupper():
inverted_s += char.lower()
else:
inverted_s += char
return inverted_s
# metodo portal
inverted_s = "" # para almacenar el nuveo str
index = 0 # para llevar el indice de str
return case_inverter_rec(s, inverted_s, index) # metodo recursivo



def test() -> None:
"""Simple self-test for Case Inverter."""
cases = [
("Hello World!", "hELLO wORLD!"),
("", ""),
("all lower", "ALL UPPER"),
("ALL UPPER", "all lower"),
("all lower", "ALL LOWER"),
("ALL UPPER", "all upper"),
("1234567890 !@#$%^&*()", "1234567890 !@#$%^&*()"),
("Python 3.12", "pYTHON 3.12"),
]
Expand Down
18 changes: 16 additions & 2 deletions exercises/celsius_to_fahrenheit/solution.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,24 @@ def celsius_to_fahrenheit(_celsius: float) -> float:
32.0
>>> celsius_to_fahrenheit(100)
212.0
>>> celsius_to_fahrenheit(-40)
>>> celsius_to_fahrenheit(-40)
-40.0
"""
return 0.0

# F(0) = 32
# F(1) = 32 + 9/5 = F(0) + 9/5
# F(2) = F(1) + 9/5 = 32 + 2*9/5
# F(n) = F(n-1) + 9/5 = 32 + n*9/5 forma recursiva

if _celsius == 0:
return 32.0

elif _celsius < 0:
return celsius_to_fahrenheit(_celsius + 1) - 9/5

else:
return celsius_to_fahrenheit(_celsius - 1) + 9/5



def test() -> None:
Expand Down
22 changes: 16 additions & 6 deletions exercises/char_frequency/solution.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,23 @@
SUBMIT = False

def char_frequency_rec(s: str, result: dict[str, int], index: int):
if index == len(s):
return result

current_char = s[index]

if current_char in result:
result[current_char] += 1
else:
result[current_char] = 1

return char_frequency_rec(s, result, index + 1)

def char_frequency(s: str) -> dict[str, int]:
"""Counts the frequency of each character in a string."""
counts = {}
for char in s:
counts[char] = counts.get(char, 0) + 1
return counts

"""Counts the frequency of each character in a string."""
result = {}
index = 0
return char_frequency_rec(s, result, index)

def test() -> None:
"""Simple self-test for Character Frequency."""
Expand Down
28 changes: 26 additions & 2 deletions exercises/count_vowels/solution.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,24 @@
import ast
from pathlib import Path

def count_vowels_rec(s: str, index: int, cant: int):
if index == len(s):
return cant

current_char = s[index].lower()
if not (current_char == 'a' or
current_char == 'e' or
current_char == 'i' or
current_char == 'o' or current_char == 'u'):
return count_vowels_rec(s, index + 1, cant)

return count_vowels_rec(s, index + 1, cant + 1)

def count_vowels(s: str):
""" Returns the number of vowels (both uppercase and lowercase) in a given string. """
return count_vowels_rec(s, 0, 0)


def test_exercise_solutions_have_asserts() -> None:
"""Verify that all exercise solution stubs have a test() function with asserts."""
root = Path(__file__).parent.parent
Expand Down Expand Up @@ -39,6 +57,12 @@ def test_exercise_solutions_have_asserts() -> None:
# Add a test function with an assert for count_vowels
def test():
# Example: assert count_vowels("hello") == 2
# For simplicity, we'll add a basic assert that checks function existence and returns true
assert True, "Placeholder assert for count_vowels test function."
assert count_vowels("hello") == 2, (f"expected 2, got: {count_vowels("hello")}")
assert count_vowels("mississipi") == 4, (f"expected 4, got: {count_vowels("mississipi")}")
assert count_vowels("AEIOU") == 5, (f"expected 5, got: {count_vowels("AEIOU")}")
assert count_vowels("AeEeiOU") == 7, (f"expected 7, got: {count_vowels("AeEeiOU")}")
print ("All test passed")

if __name__ == "__main__":
test()

Loading