Created
May 18, 2025 16:08
-
-
Save dmaldonado8/c01e7f4a9e4a3e0cdf16cf3431c20693 to your computer and use it in GitHub Desktop.
Torre de hanoi
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| A = [4, 3, 2, 1] # Torre origen | |
| B = [] # Torre destino | |
| C = [] # Torre auxiliar | |
| def mover(origen, destino): | |
| if not origen: | |
| origen.append(destino.pop()) | |
| elif not destino: | |
| destino.append(origen.pop()) | |
| elif origen[-1] < destino[-1]: | |
| destino.append(origen.pop()) | |
| else: | |
| origen.append(destino.pop()) | |
| def hanoi(n, A, B, C): | |
| torres = [A, B, C] | |
| # Si el número de discos es par, intercambiamos las torres destino y auxiliar | |
| if n % 2 == 0: | |
| B, C = C, B | |
| total_movimientos = 2 ** n - 1 | |
| for i in range(1, total_movimientos + 1): | |
| if i % 3 == 1: | |
| mover(A, B) | |
| elif i % 3 == 2: | |
| mover(A, C) | |
| else: | |
| mover(C, B) | |
| # Ejecutamos | |
| hanoi(len(A), A, B, C) | |
| # Mostramos el resultado final | |
| print("A:", A) | |
| print("B:", B) | |
| print("C:", C) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| A = [4, 3, 2, 1] | |
| B = [] | |
| C = [] | |
| def mover(disco, origen, destino): | |
| if destino and destino[-1] < disco: | |
| raise ValueError("No se puede colocar un disco más grande sobre uno más pequeño.") | |
| destino.append(disco) | |
| origen.pop() | |
| def hanoi(pos, origen, destino, aux): | |
| if pos == 1: | |
| if destino and destino[-1] < origen[-1]: | |
| print("Error") | |
| raise ValueError("No se puede colocar un disco más grande sobre uno más pequeño.") | |
| destino.append(origen[-1]) | |
| origen.pop() | |
| else: | |
| hanoi(pos - 1, origen, aux, destino) | |
| if destino and destino[-1] < origen[-1]: | |
| print("Error") | |
| raise ValueError("No se puede colocar un disco más grande sobre uno más pequeño.") | |
| destino.append(origen[-1]) | |
| origen.pop() | |
| hanoi(pos - 1, aux, destino, origen) | |
| hanoi(4, A, B, C) | |
| print(A, B, C) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment