1+ # /*
2+ # * EJERCICIO:
3+ # * He presentado mi proyecto más importante del año: mouredev pro.
4+ # * Un campus para la comunidad, que lanzaré en octubre, donde estudiar
5+ # * programación de una manera diferente.
6+ # * Cualquier persona suscrita a la newsletter de https://mouredev.pro
7+ # * accederá a sorteos mensuales de suscripciones, regalos y descuentos.
8+ # *
9+ # * Desarrolla un programa que lea los registros de un fichero .csv y
10+ # * seleccione de manera aleatoria diferentes ganadores.
11+ # * Requisitos:
12+ # * 1. Crea un .csv con 3 columnas: id, email y status con valor "activo"
13+ # * o "inactivo" (y datos ficticios).
14+ # * Ejemplo: 1 | test@test.com | activo
15+ # * 2 | test2@test.com | inactivo
16+ # * (El .csv no debe subirse como parte de la corrección)
17+ # * 2. Recupera los datos desde el programa y selecciona email aleatorios.
18+ # * Acciones:
19+ # * 1. Accede al fichero .csv y selecciona de manera aleatoria un email
20+ # * ganador de una suscripción, otro ganador de un descuento y un último
21+ # * ganador de un libro (sólo si tiene status "activo" y no está repetido).
22+ # * 2. Muestra los emails ganadores y su id.
23+ # * 3. Ten en cuenta que la primera fila (con el nombre de las columnas)
24+ # * no debe tenerse en cuenta.
25+ # */
26+ import os .path
27+ import csv
28+ import uuid
29+ import random
30+
31+
32+ class Subscriptor ():
33+ """
34+ Clase que representa a un subscriptor.
35+ """
36+ __headers = ['email' , 'status' ,'id' ]
37+
38+ def __init__ (self ,email : str , status : bool , id = uuid .uuid1 ()) -> None :
39+ self .id = id
40+ self .email = email
41+ self .status = status
42+
43+ def __str__ (self ) -> str :
44+
45+ estado = "activo" if self .status else "inactivo"
46+
47+ return f"El subscritor { self .id } - { self .email } - { estado } "
48+
49+ @classmethod
50+ def get_headers (cls ):
51+ return cls .__headers
52+
53+ class CSVFile ():
54+ """
55+ Clase que representa a un CSV.
56+ """
57+
58+ __path_file = "subscriptores.csv"
59+ __subscriptores = []
60+
61+ def __init__ (self )-> None :
62+
63+ if self .check_file ():
64+ self .cargar_datos ()
65+ else :
66+ self .crear_fichero ()
67+
68+ def check_file (self )-> bool :
69+ return True if os .path .isfile (self .__path_file ) else False
70+
71+ def add_subscriptor (self , subscriptor : Subscriptor )-> bool :
72+ if any ([value for value in self .__subscriptores if value .email == subscriptor .email ]):
73+ print (f'el subscriptor { subscriptor .email } ya existe por lo tanto no se añadirá.' )
74+ return False
75+ self .__subscriptores .append (subscriptor )
76+ return True
77+
78+ def cargar_datos (self )-> bool :
79+ print (f"Cargando fichero { self .__path_file } ...." )
80+ try :
81+ self .__subscriptores = []
82+ with open (self .__path_file , 'r' , encoding = 'utf-8' ) as file :
83+ reader = csv .DictReader (file )
84+ for line in reader :
85+ status = True if line [Subscriptor .get_headers ()[1 ]] == "True" else False
86+ subscriptor = Subscriptor (line [Subscriptor .get_headers ()[0 ]], status , line [Subscriptor .get_headers ()[2 ]])
87+ self .__subscriptores .append (subscriptor )
88+
89+ except Exception as e :
90+ print (f"No se ha podido cargar los datos { e } " )
91+ print ("Creando nuevo fichero...." )
92+ self .crear_fichero ()
93+
94+ def crear_fichero (self )-> bool :
95+ try :
96+ with open (self .__path_file , 'w' , newline = '' , encoding = 'utf-8' ) as file :
97+ writer = csv .DictWriter (file , fieldnames = Subscriptor .get_headers ())
98+ writer .writeheader ()
99+ except Exception as e :
100+ print (f"Ha habido un error al crear el fichero { e } " )
101+ return False
102+ return True
103+
104+ def guardar_datos (self )-> bool :
105+
106+ if len (self .__subscriptores ) != 0 :
107+ try :
108+ with open (self .__path_file , 'w' , newline = '' , encoding = 'utf-8' ) as file :
109+ writer = csv .DictWriter (file , fieldnames = Subscriptor .get_headers ())
110+
111+ writer .writeheader ()
112+
113+ for subscriptor in self .__subscriptores :
114+ writer .writerow ({
115+ 'email' : subscriptor .email ,
116+ 'status' : subscriptor .status ,
117+ 'id' : subscriptor .id
118+ })
119+ except Exception as e :
120+ print (f"No se ha podido guardar los datos { e } " )
121+ return False
122+ else :
123+ return False
124+
125+ return True
126+
127+ def leer_datos (self )-> None :
128+ if len (self .__subscriptores ) != 0 :
129+
130+ for subscriptor in self .__subscriptores :
131+
132+ print (subscriptor )
133+
134+ def generar_ganador (self ) -> Subscriptor :
135+
136+ return random .choice (self .__subscriptores )
137+
138+ def sorteo (self ) -> None :
139+ ganadores = []
140+ def backtracking (ganadores_provicionales : list , indice : int ):
141+ if len (ganadores_provicionales ) == 3 :
142+ ganadores .extend (ganadores_provicionales )
143+ return
144+ if indice >= len (self .__subscriptores ):
145+ return
146+
147+ for i in range (indice , len (self .__subscriptores )):
148+ subscriptor_random = random .choice (self .__subscriptores )
149+ if subscriptor_random not in ganadores_provicionales and subscriptor_random .status :
150+ ganadores_provicionales .append (subscriptor_random )
151+ backtracking (ganadores_provicionales , i + 1 )
152+ if len (ganadores ) == 3 :
153+ return
154+ ganadores_provicionales .pop ()
155+
156+ if len ([subs for subs in self .__subscriptores if subs .status ]) > 3 :
157+ backtracking ([],0 )
158+
159+ if len (ganadores ) == 3 :
160+ print (f"El ganador de la subscripción es: { ganadores [0 ]} " )
161+ print (f"El ganador del descuento es: { ganadores [1 ]} " )
162+ print (f"El ganador del libro es: { ganadores [2 ]} " )
163+ else :
164+ print ("No se ha podido encontrar una combinación ganadora, intentalo otra vez." )
165+ else :
166+ print ("No tenemos suficientes subscriptores activos para hacer el sorteo." )
167+
168+
169+ csv_gestion = CSVFile ()
170+
171+ subscriptor_1 = Subscriptor ('sub10@gmail.com' ,True )
172+ subscriptor_2 = Subscriptor ('sub0@gmail.com' ,True )
173+ subscriptor_3 = Subscriptor ('sub2@gmail.com' ,False )
174+ subscriptor_4 = Subscriptor ('sub1@gmail.com' ,True )
175+ subscriptor_5 = Subscriptor ('sub3@gmail.com' ,False )
176+
177+
178+
179+ csv_gestion .add_subscriptor (subscriptor_1 )
180+ csv_gestion .add_subscriptor (subscriptor_2 )
181+ csv_gestion .add_subscriptor (subscriptor_3 )
182+ csv_gestion .add_subscriptor (subscriptor_4 )
183+ csv_gestion .add_subscriptor (subscriptor_5 )
184+
185+
186+
187+ # csv_gestion.guardar_datos()
188+
189+ #csv_gestion.leer_datos()
190+ csv_gestion .sorteo ()
0 commit comments