



















Prepara tus exámenes y mejora tus resultados gracias a la gran cantidad de recursos disponibles en Docsity
Gana puntos ayudando a otros estudiantes o consíguelos activando un Plan Premium
Esta página no es visible en la vista previa
¡No te pierdas las partes importantes!




















Ejercicios de Funciones, Recursividad y ´Ambito de Variables
(Continuaci´on)
Ejercicios Avanzados de Algoritmos (Continuaci´on)
1 # Variable global para contar llamadas 2 contador_llamadas = 0 3 4 def factorial ( n ) : 5 global contador_llamadas 6 contador_llamadas += 1 7 8 if not isinstance (n , int ) or n < 0: 9 return - 10 if n == 0: 11 return 1 12 return n * factorial (n -1) 13
1 def validar_entero ( num ) : 2 return isinstance ( num , int ) 3 4 def suma_digitos ( num ) : 5 if not validar_entero ( num ) : 6 return " Error : No es entero " 7 8 suma = 0 # Variable local 9 num = abs ( num ) 10 while num > 0: 11 suma += num % 10 12 num = num // 10 13 return suma 14
1 memo = {0: 0 , 1: 1} # Diccionario global 2 3 def fibonacci ( n ) : 4 if n not in memo : 5 memo [ n ] = fibonacci (n -1) + fibonacci (n -2) 6 return memo [ n ] 7
7 return base * potencia ( base , exponente -1) 8
1 def decimal_a_binario ( n ) : 2 if n <= 1: 3 return str ( n ) 4 return decimal_a_binario ( n // 2) + str ( n % 2) 5
1 def limpiar_cadena ( cadena ) : 2 return ’ ’. join ( c. lower () for c in cadena if c. isalnum () ) 3 4 def es_palindromo ( cadena ) : 5 cadena_limpia = limpiar_cadena ( cadena ) 6 return cadena_limpia == cadena_limpia [:: -1] 7
1 def mcd (a , b ) : 2 return a if b == 0 else mcd (b , a % b ) 3
1 def ordenar_lista ( lista ) : 2 if len ( lista ) <= 1: 3 return lista 4 pivote = lista [ len ( lista ) //2] 5 menores = [ x for x in lista if x < pivote ] 6 iguales = [ x for x in lista if x == pivote ] 7 mayores = [ x for x in lista if x > pivote ] 8 return ordenar_lista ( menores ) + iguales + ordenar_lista ( mayores ) 9
1 saldo = 1000 # Variable global 2 3 def depositar ( monto ) : 4 global saldo 5 saldo += monto 6 return saldo 7 8 def retirar ( monto ) : 9 global saldo 10 if monto > saldo : 11 return " Saldo insuficiente " 12 saldo -= monto 13 return saldo 14 15 def c a j e r o _ a u t o m t i c o () : 16 return { " saldo " : saldo , " depositar " : depositar , " retirar " : retirar } 17
1 pasos = 0 # Variable global 2 3 def collatz ( n ) : 4 global pasos 5 pasos += 1 6 if n == 1: 7 return [1] 8 elif n % 2 == 0: 9 return [ n ] + collatz ( n // 2) 10 else : 11 return [ n ] + collatz (3 * n + 1) 12
1 import re 2 3 def validar_email ( email ) : 4 patron = r ’ ^[\ w . -]+ @ [\ w . -]+.\ w + $ ’ 5 return bool ( re. match ( patron , email ) ) 6
1 import math 2 3 def area_circulo ( radio ) : 4 return math. pi * radio ** 2 5 6 def perimetro_circulo ( radio ) : 7 return 2 * math. pi * radio 8 9 def area_rectangulo ( base , altura ) : 10 return base * altura 11 12 def perimetro_rectangulo ( base , altura ) : 13 return 2 * ( base + altura ) 14 15 def area_triangulo ( base , altura ) : 16 return ( base * altura ) / 2 17 18 def perimetro_triangulo ( lado1 , lado2 , lado3 ) : 19 return lado1 + lado2 + lado 20 21 def calcular_geometria ( figura , ** kwargs ) : 22 if figura == " circulo " : 23 return { 24 " area " : area_circulo ( kwargs [ " radio " ]) , 25 " perimetro " : perimetro_circulo ( kwargs [ " radio " ]) 26 } 27 elif figura == " rectangulo " : 28 return { 29 " area " : area_rectangulo ( kwargs [ " base " ] , kwargs [ " altura " ]) , 30 " perimetro " : perimetro_rectangulo ( kwargs [ " base " ] , kwargs [ " altura " ]) 31 } 32 elif figura == " triangulo " : 33 return { 34 " area " : area_triangulo ( kwargs [ " base " ] , kwargs [ " altura " ]) , 35 " perimetro " : perimetro_triangulo ( kwargs [ " lado1 " ] , kwargs [ " lado2 " ] , kwargs [ " lado3 " ]) 36 } 37
1 import random 2 3 mazo = [ f " { valor } -{ palo } " for valor in range (1 , 14) 4 for palo in [ " corazones " , " diamantes " , " treboles " , " picas " ]] 5 6 def barajar () : 7 random. shuffle ( mazo ) 8 9 def repartir_cartas ( jugadores , cartas_por_jugador ) : 10 barajar () 11 return { f " Jugador { i +1} " : mazo [ i * cartas_por_jugador :( i +1) * cartas_por_jugador ] 12 for i in range ( jugadores ) } 13
Soluciones de Ejercicios (Continuaci´on)
1 def validar_desplazamiento ( n ) : 2 return isinstance (n , int ) and 1 <= n <= 25 3 4 def cifrar_cesar ( texto , desplazamiento ) : 5 if not validar_desplazamiento ( desplazamiento ) : 6 return " Desplazamiento i n v l i d o " 7 8 resultado = [] 9 for c in texto : 10 if c. isalpha () : 11 base = ord ( ’A ’) if c. isupper () else ord ( ’a ’) 12 nuevo_char = chr (( ord ( c ) - base + desplazamiento ) % 26 + base ) 13 resultado. append ( nuevo_char ) 14 else : 15 resultado. append ( c ) 16 return ’ ’. join ( resultado ) 17
1 secuencia_fib = [] # Variable global 2 3 def fibonacci_inversa ( n ) : 4 global secuencia_fib 5 if n <= 0: 6 return [] 7 elif n == 1: 8 return [0] 9 elif n == 2: 10 return [1 , 0] 11 12 fib = fibonacci_inversa (n -1) 13 nuevo_valor = fib [0] + fib [1] if len ( fib ) >= 2 else 1 14 return [ nuevo_valor ] + fib 15
1 def calcular_rpn ( expresion ) : 2 pila = [] 3 operadores = {
4 ’+ ’: lambda x , y : x + y , 5 ’ - ’: lambda x , y : x - y , 6 ’* ’: lambda x , y : x * y , 7 ’/ ’: lambda x , y : x / y 8 } 9 10 for token in expresion : 11 if token in operadores : 12 y = pila. pop () 13 x = pila. pop () 14 pila. append ( operadores [ token ]( x , y ) ) 15 else : 16 pila. append ( float ( token ) ) 17 return pila [0] 18
1 def parentesis_balanceados (s , pila = None ) : 2 if pila is None : 3 pila = [] 4 pares = { ’) ’: ’( ’ , ’] ’: ’[ ’ , ’} ’: ’{ ’} 5 6 if not s : 7 return len ( pila ) == 0 8 9 c = s [0] 10 if c in pares. values () : 11 return parentesis_balanceados ( s [1:] , pila + [ c ]) 12 elif c in pares. keys () : 13 if not pila or pila [ -1] != pares [ c ]: 14 return False 15 return parentesis_balanceados ( s [1:] , pila [: -1]) 16 else : 17 return parentesis_balanceados ( s [1:] , pila ) 18
1 def resolver_laberinto ( laberinto , x =0 , y =0 , camino = None ) : 2 if camino is None : 3 camino = [] 4 if x < 0 or y < 0 or x >= len ( laberinto ) or y >= len ( laberinto [0]) : 5 return False 6 if laberinto [ x ][ y ] == ’S ’: 7 return camino + [( x , y ) ] 8 if laberinto [ x ][ y ] != ’ ’: 9 return False 10 11 laberinto [ x ][ y ] = ’V ’ # Marcar como visitado 12 for dx , dy in [(0 ,1) , (1 ,0) , (0 , -1) , ( -1 ,0) ]: 13 resultado = resolver_laberinto ( laberinto , x + dx , y + dy , camino + [( x , y ) ]) 14 if resultado : 15 return resultado 16 return False 17
1 def convertir_base ( num , base_actual , base_destino ) : 2 digitos = " 0123456789 ABCDEFGHIJKLMNOPQRSTUVWXYZ " 3
3 def coeficiente_binomial (n , k ) : 4 if k == 0 or k == n : 5 return 1 6 if (n , k ) in memo : 7 return memo [( n , k ) ] 8 9 res = coeficiente_binomial (n -1 , k -1) + coeficiente_binomial (n -1 , k ) 10 memo [( n , k ) ] = res 11 return res 12
1 import random 2 3 def adivina_numero ( intentos =5) : 4 objetivo = random. randint (1 , 100) 5 6 def jugar ( intentos_restantes ) : 7 if intentos_restantes == 0: 8 print ( f " Perdiste! El n m e r o era { objetivo } " ) 9 return 10 11 guess = int ( input ( " Adivina el n m e r o (1 -100) : " ) ) 12 if guess == objetivo : 13 print ( " Correcto! " ) 14 elif guess < objetivo : 15 print ( " M s alto " ) 16 jugar ( intentos_restantes - 1) 17 else : 18 print ( " M s bajo " ) 19 jugar ( intentos_restantes - 1) 20 21 jugar ( intentos ) 22
1 def merge_sort ( arr ) : 2 if len ( arr ) <= 1: 3 return arr 4 5 medio = len ( arr ) // 2 6 izquierda = merge_sort ( arr [: medio ]) 7 derecha = merge_sort ( arr [ medio :]) 8 9 return mezclar ( izquierda , derecha ) 10 11 def mezclar ( izq , der ) : 12 resultado = [] 13 i = j = 0 14 while i < len ( izq ) and j < len ( der ) : 15 if izq [ i ] < der [ j ]: 16 resultado. append ( izq [ i ]) 17 i += 1 18 else : 19 resultado. append ( der [ j ]) 20 j += 1 21 resultado. extend ( izq [ i :]) 22 resultado. extend ( der [ j :]) 23 return resultado 24
1 def evaluar_expresion ( expresion ) : 2 def evaluar ( tokens ) : 3 token = tokens. pop () 4 if token. isdigit () : 5 return int ( token ) 6 a = evaluar ( tokens ) 7 b = evaluar ( tokens ) 8 if token == ’+ ’: return a + b 9 if token == ’ - ’: return a - b 10 if token == ’* ’: return a * b 11 if token == ’/ ’: return a / b 12 13 tokens = expresion. split () [:: -1] 14 return evaluar ( tokens ) 15
1 def subconjuntos ( elems ) : 2 if not elems : 3 return [[]] 4 5 primero = elems [0] 6 resto = subconjuntos ( elems [1:]) 7 return resto + [[ primero ] + sub for sub in resto ] 8
1 def raiz_babilonica (n , estimado = None , precision =1 e -6) : 2 if estimado is None : 3 estimado = n / 2. 4 nuevo_estimado = ( estimado + n / estimado ) / 2 5 if abs ( nuevo_estimado - estimado ) < precision : 6 return nuevo_estimado 7 return raiz_babilonica (n , nuevo_estimado , precision ) 8
1 cinta = [ ’0 ’] * 20 + [ ’1 ’] * 20 # Ejemplo : 0^ n1 ^ n 2 posicion = 0 3 estado = ’ q0 ’ 4 5 def maquina_turing () : 6 global cinta , posicion , estado 7 8 if estado == ’ q_accept ’: 9 return True 10 if estado == ’ q_reject ’: 11 return False 12 13 simbolo = cinta [ posicion ] 14 15 # Transiciones para 0^ n1 ^ n 16 if estado == ’ q0 ’ and simbolo == ’0 ’: 17 cinta [ posicion ] = ’X ’ 18 posicion += 1 19 estado = ’ q1 ’ 20 elif estado == ’ q1 ’ and simbolo == ’0 ’: 21 posicion += 1 22 elif estado == ’ q1 ’ and simbolo == ’Y ’:
31 if nodo. char : 32 codigos [ nodo. char ] = codigo 33 else : 34 asignar_codigos ( nodo. izq , codigo + ’0 ’) 35 asignar_codigos ( nodo. der , codigo + ’1 ’) 36 37 asignar_codigos ( raiz ) 38 return ’ ’. join ( codigos [ char ] for char in texto ) 39
1 def mochila ( pesos , valores , capacidad , n = None , memo = None ) : 2 if memo is None : 3 memo = {} 4 if n is None : 5 n = len ( pesos ) 6 7 if n == 0 or capacidad == 0: 8 return 0 9 if (n , capacidad ) in memo : 10 return memo [( n , capacidad ) ] 11 12 if pesos [n -1] > capacidad : 13 resultado = mochila ( pesos , valores , capacidad , n -1 , memo ) 14 else : 15 incluir = valores [n -1] + mochila ( pesos , valores , capacidad - pesos [n -1] , n -1 , memo ) 16 excluir = mochila ( pesos , valores , capacidad , n -1 , memo ) 17 resultado = max ( incluir , excluir ) 18 19 memo [( n , capacidad ) ] = resultado 20 return resultado 21
1 def tiene_ciclos ( grafo ) : 2 visitados = set () 3 4 def dfs ( nodo , padre ) : 5 visitados. add ( nodo ) 6 for vecino in grafo [ nodo ]: 7 if vecino not in visitados : 8 if dfs ( vecino , nodo ) : 9 return True 10 elif vecino != padre : 11 return True 12 return False 13 14 for nodo in grafo : 15 if nodo not in visitados : 16 if dfs ( nodo , None ) : 17 return True 18 return False 19
Soluciones Avanzadas de Algoritmos
1 def cuadrado_magico ( n ) : 2 matriz = [[0] * n for _ in range ( n ) ] 3 4 def llenar (i , j , num ) : 5 if num > n **2: 6 return True 7 if i < 0 and j == n : 8 i , j = 0 , n - 9 else : 10 if i < 0: 11 i = n - 12 if j == n : 13 j = 0 14 if matriz [ i ][ j ]: 15 return llenar ( i +1 , j -2 , num ) 16 17 matriz [ i ][ j ] = num 18 return llenar (i -1 , j +1 , num +1) 19 20 llenar ( n //2 , n -1 , 1) 21 return matriz 22
1 def resolver_sudoku ( tablero ) : 2 def es_valido (i , j , num ) : 3 for x in range (9) : 4 if tablero [ i ][ x ] == num or tablero [ x ][ j ] == num : 5 return False 6 box_i , box_j = i //33 , j //3 7 for x in range (3) : 8 for y in range (3) : 9 if tablero [ box_i + x ][ box_j + y ] == num : 10 return False 11 return True 12 13 for i in range (9) : 14 for j in range (9) : 15 if tablero [ i ][ j ] == 0: 16 for num in range (1 , 10) : 17 if es_valido (i , j , num ) : 18 tablero [ i ][ j ] = num 19 if resolver_sudoku ( tablero ) : 20 return True 21 tablero [ i ][ j ] = 0 22 return False 23 return True 24
1 def automatas_celulares (n , patron_inicial ) : 2 regla_110 = { 3 ’ 111 ’: ’0 ’ , ’ 110 ’: ’1 ’ , ’ 101 ’: ’1 ’ , 4 ’ 100 ’: ’0 ’ , ’ 011 ’: ’1 ’ , ’ 010 ’: ’1 ’ , 5 ’ 001 ’: ’1 ’ , ’ 000 ’: ’0 ’ 6 } 7 8 def siguiente_generacion ( actual ) : 9 nuevo = [] 10 for i in range ( len ( actual ) ) : 11 vecindad = actual [i -1] + actual [ i ] + actual [( i +1) %len ( actual ) ]