

















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!


















1 def cifrado_cesar () : 2 desplazamiento = 3 3 with open ( ’ mensaje. txt ’ , ’r ’) as f : 4 texto = f. read () 5 cifrado = ’ ’. join ( 6 chr (( ord ( char ) - 97 + desplazamiento ) % 26 + 97) if char. islower () else 7 chr (( ord ( char ) - 65 + desplazamiento ) % 26 + 65) if char. isupper () else char 8 for char in texto 9 ) 10 11 with open ( ’ cifrado. bin ’ , ’ wb ’) as bin_file : 12 bin_file. write ( cifrado. encode () ) 13 14 cifrado_cesar ()
1 def es_palindromo ( palabra ) : 2 return palabra == palabra [:: -1] 3 4 def buscar_palindromos () : 5 with open ( ’ palabras. txt ’ , ’r ’) as f : 6 palabras = f. read (). split () 7 palindromos = [( p , len ( p ) ) for p in palabras if es_palindromo ( p. lower () ) ] 8 9 with open ( ’ palindromos. txt ’ , ’w ’) as output : 10 for p , l in palindromos : 11 output. write ( f " { p }: { l }\ n " ) 12 13 buscar_palindromos ()
1 import struct 2 3 def ordenar_numeros () : 4 with open ( ’ numeros. bin ’ , ’ rb ’) as bin_file : 5 datos = bin_file. read () 6 numeros = struct. unpack ( ’i ’ * ( len ( datos ) // 4) , datos ) 7 8 numeros_ordenados = sorted ( numeros ) 9 10 with open ( ’ ordenados. txt ’ , ’w ’) as txt_file : 11 for num in numeros_ordenados : 12 txt_file. write ( f " { num }\ n " ) 13 14 ordenar_numeros ()
1 import csv 2 import pickle 3 4 def calcular_ventas () : 5 ventas_por_producto = {} 6 7 with open ( ’ ventas. csv ’ , ’r ’) as csv_file : 8 reader = csv. DictReader ( csv_file ) 9 for row in reader : 10 producto = row [ ’ Producto ’]
11 total = float ( row [ ’ Cantidad ’ ]) * float ( row [ ’ Precio ’ ]) 12 ventas_por_producto [ producto ] = ventas_por_producto. get ( producto , 0) + total 13 14 with open ( ’ totales. bin ’ , ’ wb ’) as bin_file : 15 pickle. dump ( ventas_por_producto , bin_file ) 16 17 calcular_ventas ()
1 import re 2 3 def extraer_emails () : 4 with open ( ’ correos. txt ’ , ’r ’) as f : 5 texto = f. read () 6 emails = re. findall ( r ’\ b [A - Za - z0 -9. _ %+ -]+ @ [A - Za - z0 -9. -]+.[ A - Z |a - z ]{2 ,}\ b ’ , texto ) 7 8 with open ( ’ emails. txt ’ , ’w ’) as output : 9 for email in emails : 10 output. write ( f " { email }\ n " ) 11 12 extraer_emails ()
1 def comprimir_rle () : 2 with open ( ’ texto. txt ’ , ’r ’) as f : 3 texto = f. read () 4 5 comprimido = [] 6 i = 0 7 while i < len ( texto ) : 8 count = 1 9 while i + 1 < len ( texto ) and texto [ i ] == texto [ i +1]: 10 i += 1 11 count += 1 12 comprimido. append ( f " { count }{ texto [ i ]} " ) 13 i += 1 14 15 with open ( ’ comprimido. bin ’ , ’ wb ’) as bin_file : 16 bin_file. write ( ’ ’. join ( comprimido ). encode () ) 17 18 comprimir_rle ()
1 import re 2 3 def v a l i d a r _ c o n t r a s e a s () : 4 with open ( ’ passwords. txt ’ , ’r ’) as f : 5 c o n t r a s e a s = f. read (). splitlines () 6 7 validas = [] 8 for pwd in c o n t r a s e a s : 9 if ( len ( pwd ) >= 8 and 10 re. search ( r ’[A - Z ] ’ , pwd ) and 11 re. search ( r ’[a - z ] ’ , pwd ) and 12 re. search ( r ’\ d ’ , pwd ) ) : 13 validas. append ( pwd ) 14 15 with open ( ’ validas. txt ’ , ’w ’) as output :
1 import csv 2 3 def convertir_temperaturas () : 4 with open ( ’ temperaturas. csv ’ , ’r ’) as csv_file : 5 reader = csv. DictReader ( csv_file ) 6 datos = list ( reader ) 7 8 with open ( ’ fahrenheit. txt ’ , ’w ’) as output : 9 for row in datos : 10 celsius = float ( row [ ’ Celsius ’ ]) 11 fahrenheit = ( celsius * 9/5) + 32 12 output. write ( f " { fahrenheit :.2 f }\ n " ) 13 14 convertir_temperaturas ()
1 import numpy as np 2 3 def sumar_matrices () : 4 with open ( ’ matriz1. bin ’ , ’ rb ’) as f1 , open ( ’ matriz2. bin ’ , ’ rb ’) as f2 : 5 matriz1 = np. load ( f1 ) 6 matriz2 = np. load ( f2 ) 7 8 resultado = matriz1 + matriz 9 10 with open ( ’ resultado. bin ’ , ’ wb ’) as output : 11 np. save ( output , resultado ) 12 13 sumar_matrices ()
1 def eliminar_duplicados () : 2 with open ( ’ lista. txt ’ , ’r ’) as f : 3 nombres = list ( set ( f. read (). splitlines () ) ) 4 5 with open ( ’ sin_duplicados. txt ’ , ’w ’) as output : 6 for nombre in sorted ( nombres ) : 7 output. write ( f " { nombre }\ n " ) 8 9 eliminar_duplicados ()
1 import csv 2 3 def generar_grafica () : 4 with open ( ’ datos_grafica. csv ’ , ’r ’) as csvfile : 5 reader = csv. DictReader ( csvfile ) 6 datos = [( row [ ’ Categoria ’] , int ( row [ ’ Valor ’ ]) ) for row in reader ] 7 8 max_val = max ( val for _ , val in datos ) 9 escala = 50 / max_val 10 11 with open ( ’ grafica. txt ’ , ’w ’) as f : 12 for categoria , valor in datos : 13 barra = ’# ’ * int ( valor * escala ) 14 f. write ( f " { categoria. ljust (15) }: { barra } { valor }\ n " ) 15 16 generar_grafica ()
1 import base 2 3 def codificar_base64 () : 4 with open ( ’ imagen. bin ’ , ’ rb ’) as bin_file : 5 datos = bin_file. read () 6 codificado = base64. b64encode ( datos ) 7 8 with open ( ’ codificado. txt ’ , ’ wb ’) as txt_file : 9 txt_file. write ( codificado ) 10 11 codificar_base64 ()
1 def buscar_subcadena () : 2 subcadena = input ( " Ingrese la subcadena a buscar : " ) 3 resultados = [] 4 5 with open ( ’ libro. txt ’ , ’r ’ , encoding = ’utf -8 ’) as f : 6 for num_linea , linea in enumerate (f , 1) : 7 if subcadena. lower () in linea. lower () : 8 resultados. append ( f " L n e a { num_linea }: { linea. strip () } " ) 9 10 with open ( ’ ocurrencias. txt ’ , ’w ’ , encoding = ’utf -8 ’) as output : 11 output. write ( " \ n ". join ( resultados ) ) 12 13 buscar_subcadena ()
1 def ordenar_alfabeticamente () : 2 with open ( ’ nombres. txt ’ , ’r ’) as f : 3 nombres = [ line. strip () for line in f if line. strip () ] 4 5 nombres_ordenados = sorted ( nombres , key = lambda x : x. lower () ) 6 7 with open ( ’ ordenados. txt ’ , ’w ’) as output : 8 output. write ( " \ n ". join ( nombres_ordenados ) ) 9 10 ordenar_alfabeticamente ()
1 def extraer_metadatos () : 2 patron = re. compile ( r ’ ^([^=]+) =(.*) $ ’) 3 valores = [] 4 5 with open ( ’ configuracion. txt ’ , ’r ’) as f : 6 for linea in f : 7 coincidencia = patron. match ( linea. strip () ) 8 if coincidencia : 9 valores. append ( coincidencia. group (2) ) 10 11 with open ( ’ valores. txt ’ , ’w ’) as output : 12 output. write ( " \ n ". join ( valores ) ) 13 14 extraer_metadatos ()
3 def encontrar_anagramas () : 4 anagramas = defaultdict ( list ) 5 6 with open ( ’ palabras. txt ’ , ’r ’) as f : 7 palabras = [ line. strip (). lower () for line in f if line. strip () ] 8 9 for palabra in palabras : 10 clave = ’ ’. join ( sorted ( palabra ) ) 11 anagramas [ clave ]. append ( palabra ) 12 13 with open ( ’ anagramas. txt ’ , ’w ’) as output : 14 for grupo in anagramas. values () : 15 if len ( grupo ) > 1: 16 output. write ( f " { ’ ’. join ( grupo ) }\ n " ) 17 18 encontrar_anagramas ()
1 def validar_tarjetas () : 2 def es_valida ( numero ) : 3 suma = 0 4 alternar = False 5 6 for d in reversed ( numero ) : 7 if not d. isdigit () : 8 continue 9 digito = int ( d ) 10 if alternar : 11 digito *= 2 12 if digito > 9: 13 digito = ( digito // 10) + ( digito % 10) 14 suma += digito 15 alternar = not alternar 16 17 return suma % 10 == 0 18 19 with open ( ’ tarjetas. txt ’ , ’r ’) as f , open ( ’ validas. txt ’ , ’w ’) as output : 20 for linea in f : 21 numero = linea. strip () 22 if es_valida ( numero ) : 23 output. write ( f " { numero }\ n " ) 24 25 validar_tarjetas ()
1 import re 2 3 def extraer_urls () : 4 patron = r ’ https ?://(?:[ -\ w .]|(?: %[\ da - fA - F ]{2}) ) +[/\ w. -]* ’ 5 6 with open ( ’ web. html ’ , ’r ’ , encoding = ’utf -8 ’) as f : 7 contenido = f. read () 8 urls = re. findall ( patron , contenido ) 9 10 with open ( ’ urls. txt ’ , ’w ’ , encoding = ’utf -8 ’) as output : 11 output. write ( " \ n ". join ( urls ) ) 12 13 extraer_urls ()
1 def generar_fibonacci () : 2 def fib ( n ) : 3 a , b = 0 , 1 4 for _ in range ( n ) : 5 yield a 6 a , b = b , a + b 7 8 numeros = list ( fib (100) ) 9 10 with open ( ’ fibonacci. bin ’ , ’ wb ’) as bin_file : 11 import struct 12 bin_file. write ( struct. pack ( ’i ’ * len ( numeros ) , * numeros ) 13 14 generar_fibonacci ()
1 from collections import Counter , defaultdict 2 import heapq 3 4 def comprimir_huffman () : 5 # I m p l e m e n t a c i n b s i c a ( v e r s i n simplificada ) 6 with open ( ’ texto. txt ’ , ’r ’) as f : 7 texto = f. read () 8 9 # Calcular frecuencias 10 frecuencias = Counter ( texto ) 11 12 # Construir rbol de Huffman 13 heap = [[ peso , [ simbolo , " " ]] for simbolo , peso in frecuencias. items () ] 14 heapq. heapify ( heap ) 15 16 while len ( heap ) > 1: 17 lo = heapq. heappop ( heap ) 18 hi = heapq. heappop ( heap ) 19 for par in lo [1:]: 20 par [1] = ’0 ’ + par [1] 21 for par in hi [1:]: 22 par [1] = ’1 ’ + par [1] 23 heapq. heappush ( heap , [ lo [0] + hi [0]] + lo [1:] + hi [1:]) 24 25 # Generar c d i g o s 26 codigos = dict ( heapq. heappop ( heap ) [1:]) 27 28 # Codificar texto 29 texto_codificado = ’ ’. join ( codigos [ caracter ] for caracter in texto ) 30 31 # Guardar resultado 32 with open ( ’ comprimido. bin ’ , ’ wb ’) as bin_file : 33 import pickle 34 pickle. dump (( codigos , texto_codificado ) , bin_file ) 35 36 comprimir_huffman ()
1 def buscar_patron_adn () : 2 patron = input ( " Ingrese el p a t r n de ADN a buscar : " ). upper () 3 resultados = [] 4
4 fechas_validas = [] 5 6 with open ( ’ fechas. txt ’ , ’r ’) as f : 7 for linea in f : 8 fecha = linea. strip () 9 try : 10 datetime. strptime ( fecha , ’ %d/ %m/ %Y ’) 11 fechas_validas. append ( fecha ) 12 except ValueError : 13 continue 14 15 with open ( ’ validas. txt ’ , ’w ’) as output : 16 output. write ( ’\ n ’. join ( fechas_validas ) ) 17 18 validar_fechas ()
1 import pickle 2 3 class Nodo : 4 def init ( self , valor ) : 5 self. izquierda = None 6 self. derecha = None 7 self. valor = valor 8 9 def insertar ( raiz , valor ) : 10 if raiz is None : 11 return Nodo ( valor ) 12 if valor < raiz. valor : 13 raiz. izquierda = insertar ( raiz. izquierda , valor ) 14 else : 15 raiz. derecha = insertar ( raiz. derecha , valor ) 16 return raiz 17 18 def buscar_arbol () : 19 with open ( ’ arbol. bin ’ , ’ rb ’) as f : 20 datos = pickle. load ( f ) 21 22 raiz = None 23 for num in datos : 24 raiz = insertar ( raiz , num ) 25 26 valor_buscar = int ( input ( " Ingrese valor a buscar : " ) ) 27 resultado = " ENCONTRADO " if buscar ( raiz , valor_buscar ) else " NO ENCONTRADO " 28 29 with open ( ’ busqueda. txt ’ , ’w ’) as output : 30 output. write ( resultado ) 31 32 def buscar ( raiz , valor ) : 33 if raiz is None : 34 return False 35 if raiz. valor == valor : 36 return True 37 return buscar ( raiz. izquierda , valor ) if valor < raiz. valor else buscar ( raiz. derecha , valor ) 38 39 buscar_arbol ()
1 import csv
2 import math 3 4 def calcular_distancias () : 5 with open ( ’ coordenadas. csv ’ , ’r ’) as csvfile : 6 reader = csv. DictReader ( csvfile ) 7 puntos = [( float ( row [ ’x ’ ]) , float ( row [ ’y ’ ]) ) for row in reader ] 8 9 distancias = [] 10 for i in range ( len ( puntos ) -1) : 11 x1 , y1 = puntos [ i ] 12 x2 , y2 = puntos [ i +1] 13 distancia = math. sqrt (( x2 - x1 ) **2 + ( y2 - y1 ) **2) 14 distancias. append ( f " Punto { i +1} a { i +2}: { distancia :.2 f } " ) 15 16 with open ( ’ distancias. txt ’ , ’w ’) as output : 17 output. write ( ’\ n ’. join ( distancias ) ) 18 19 calcular_distancias ()
1 import csv 2 import random 3 from faker import Faker 4 5 def generar_csv () : 6 fake = Faker () 7 with open ( ’ datos. csv ’ , ’w ’ , newline = ’ ’) as csvfile : 8 writer = csv. writer ( csvfile ) 9 writer. writerow ([ ’ ID ’ , ’ Nombre ’ , ’ Edad ’ , ’ Salario ’ ]) 10 11 for i in range (1000) : 12 nombre = fake. name () 13 edad = random. randint (18 , 65) 14 salario = round ( random. uniform (1000 , 10000) , 2) 15 writer. writerow ([ i +1 , nombre , edad , salario ]) 16 17 generar_csv ()
1 import re 2 3 def extraer_hashtags () : 4 with open ( ’ tweets. txt ’ , ’r ’ , encoding = ’utf -8 ’) as f : 5 contenido = f. read () 6 hashtags = re. findall ( r ’ #\ w + ’ , contenido ) 7 8 with open ( ’ hashtags. txt ’ , ’w ’ , encoding = ’utf -8 ’) as output : 9 output. write ( ’\ n ’. join ( set ( hashtags ) ) ) 10 11 extraer_hashtags ()
1 def cifrado_xor () : 2 clave = input ( " Ingrese clave para cifrado XOR : " ). encode () 3 4 with open ( ’ secreto. bin ’ , ’ rb ’) as f : 5 datos = f. read () 6
6 7 nombres = re. findall ( r ’\ b [A - Z ][ a - z ]+\ b ’ , contenido ) 8 nombres_filtrados = [ n for n in nombres if len ( n ) > 2] # Filtrar palabras cortas 9 10 with open ( ’ nombres. txt ’ , ’w ’ , encoding = ’utf -8 ’) as output : 11 output. write ( ’\ n ’. join ( set ( nombres_filtrados ) ) ) 12 13 extraer_nombres_propios ()
1 import math 2 import struct 3 4 def calcular_mcd () : 5 with open ( ’ numeros. bin ’ , ’ rb ’) as f : 6 datos = f. read () 7 numeros = struct. unpack ( ’i ’ *( len ( datos ) //4) , datos ) 8 9 resultados = [] 10 for i in range (0 , len ( numeros ) , 2) : 11 a , b = numeros [ i ] , numeros [ i +1] 12 mcd = math. gcd (a , b ) 13 resultados. append ( f " MCD ({ a } , { b }) = { mcd } " ) 14 15 with open ( ’ mcd. txt ’ , ’w ’) as output : 16 output. write ( ’\ n ’. join ( resultados ) ) 17 18 calcular_mcd ()
1 import qrcode 2 import os 3 4 def generar_qrs () : 5 os. makedirs ( ’ qrs ’ , exist_ok = True ) 6 7 with open ( ’ enlaces. txt ’ , ’r ’) as f : 8 lineas = [ line. strip () for line in f if line. strip () ] 9 10 for i , texto in enumerate ( lineas , 1) : 11 img = qrcode. make ( texto ) 12 img. save ( f ’ qrs / qr_ { i }. png ’) 13 14 generar_qrs ()
1 def es_armstrong ( n ) : 2 digitos = [ int ( d ) for d in str ( n ) ] 3 potencia = len ( digitos ) 4 return n == sum ( d ** potencia for d in digitos ) 5 6 def buscar_armstrong () : 7 with open ( ’ numeros. txt ’ , ’r ’) as f : 8 numeros = [ int ( line. strip () ) for line in f if line. strip (). isdigit () ] 9 10 armstrongs = [ str ( n ) for n in numeros if es_armstrong ( n ) ] 11 12 with open ( ’ armstrong. txt ’ , ’w ’) as output :
13 output. write ( ’\ n ’. join ( armstrongs ) ) 14 15 buscar_armstrong ()
1 import xml. etree. ElementTree as ET 2 3 def procesar_xml () : 4 tree = ET. parse ( ’ datos. xml ’) 5 root = tree. getroot () 6 7 resultados = [] 8 for elemento in root. findall ( ’ .// item ’) : 9 nombre = elemento. get ( ’ nombre ’ , ’ ’) 10 valor = elemento. find ( ’ valor ’). text if elemento. find ( ’ valor ’) is not None else ’ ’ 11 resultados. append ( f " { nombre }: { valor } " ) 12 13 with open ( ’ extraidos. txt ’ , ’w ’ , encoding = ’utf -8 ’) as output : 14 output. write ( ’\ n ’. join ( resultados ) ) 15 16 procesar_xml ()
1 import secrets 2 import string 3 4 def g e n e r a r _ c o n t r a s e a s () : 5 caracteres = string. ascii_letters + string. digits + string. punctuation 6 c o n t r a s e a s = [ ’ ’. join ( secrets. choice ( caracteres ) for _ in range (12) ) for _ in range (50) ] 7 8 with open ( ’ passwords. bin ’ , ’ wb ’) as f : 9 import pickle 10 pickle. dump ( c o n t r a s e a s , f ) 11 12 g e n e r a r _ c o n t r a s e a s ()
1 def es_capicua ( n ) : 2 s = str ( n ) 3 return s == s [:: -1] 4 5 def buscar_capicuas () : 6 with open ( ’ datos. bin ’ , ’ rb ’) as f : 7 import struct 8 datos = f. read () 9 numeros = struct. unpack ( ’i ’ *( len ( datos ) //4) , datos ) 10 11 capicuas = [ str ( n ) for n in numeros if es_capicua ( n ) ] 12 13 with open ( ’ capicua. txt ’ , ’w ’) as f : 14 f. write ( ’\ n ’. join ( capicuas ) ) 15 16 buscar_capicuas ()