Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Logica para leer el CSV #6

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
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
205 changes: 205 additions & 0 deletions csv_management.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,205 @@
"""_summary_

Returns:
_type_: _description_
"""
import csv
import dataclasses
from pydantic import BaseModel, Field, constr
from typing import List, Optional


class Student(BaseModel):
""" Estos son los atributos asociados a un estudiante
"""
first_name: constr(to_lower=True) = Field(alias='nombre')
last_name: constr(to_lower=True) = Field(alias='apellido')
city: constr(to_lower=True) = Field(alias='ciudad')
country: constr(to_lower=True) = Field(alias='pais')
age: int = Field(alias='edad')
career: constr(to_lower=True) = Field(alias='carrera')


@dataclasses.dataclass
class CsvManagement:
"""Clase para manejar todo lo relacionado a la informacion del CSV.
"""
file_name: str

def __post_init__(self) -> Optional[List[Student]]:
with open(self.file_name, newline='', encoding='UTF-8') as f:
csv_info = csv.DictReader(f)
self.list_of_students = [Student(**row) for row in csv_info]

def get_student_by_name(self, student_name: str) -> Optional[Student]:
""" Metodo para buscar un estudiante por su nombre

Args:
student_name (str): Nombre del estudiante

Returns:
Optional[Student]: Toda la informacion relacionada al estudiante
"""
for student in self.list_of_students:
if student.first_name == student_name.lower():
return student

return None

def get_students_by_city(self, city: str) -> Optional[List[Student]]:
"""Metodo para buscar los estudiantes de una ciudad

Args:
city (str): Nombre de la ciudad

Returns:
Optional[List[Student]]: Lista de estudiantes asociada a una ciudad
"""
return [
student.first_name.capitalize()
for student in self.list_of_students
if student.city == city.lower()
]

def get_students_by_country(self, country: str) -> Optional[List[Student]]:
"""Metodo para buscar los estudiantes de un pais

Args:
country (str): Nombre del pais

Returns:
Optional[List[Student]]: Lista de estudiantes asociada a un pais
"""
return [
student.first_name.capitalize()
for student in self.list_of_students
if student.country == country.lower()
]

def get_students_by_age_range(
self,
min_age: int,
max_age: int
) -> Optional[List[Student]]:
"""Metodo para obtener la lista de estudiantes de un rango de edades

Args:
min_age (int): Edad minima
max_age (int): Edad maxima

Returns:
Optional[List[Student]]: Lista de estudiantes de determinado rango
de edades
"""
return [
student.first_name.capitalize()
for student in self.list_of_students
if min_age >= student.age <= max_age
]

def get_cities(self) -> Optional[List[str]]:
"""Metodo para obtener todas las ciudades

Returns:
Optional[set[str]]: Set con el nombre de las ciudades
"""
return set(
student.city.title() for student in self.list_of_students
)

def get_average_age_by_career(
self,
career: str
) -> int:
"""Metodo para obtener promedio de edad por carrera

Args:
career (str): Nombre de la carrera

Returns:
int: Promedio
"""
list_students_by_career = [student.age
for student in self.list_of_students
if student.career == career.lower()]
if list_students_by_career:
return (sum(age for age in list_students_by_career) /
len(list_students_by_career))
return 0

def get_student_is_below_or_above_by_career_average_age(
self,
student_name: str
) -> str:
"""_summary_

Args:
student_name (str): _description_

Returns:
str: _description_
"""
student = self.get_student_by_name(student_name)
if student:
career_average = self.get_average_age_by_career(student.career)

if student.age > career_average:
return f'El estudiante {student.first_name.title()} esta sobre el promedio'

return f'El estudiante {student.first_name.title()} esta por debajo del promedio'

return f'El estudiante {student_name} no existe!!!'

def sort_students_by_age(self):
"""_summary_

Returns:
_type_: _description_
"""
age_groups = {
'18-25': [],
'26-35': [],
'35+': []
}

for student in self.list_of_students:
group = None

if 18 <= student.age <= 25:
group = '18-25'
elif 26 <= student.age <= 35:
group = '26-35'
else:
group = '35+'

age_groups[group].append(student.first_name.capitalize())

return age_groups

def get_city_with_most_careers(self) -> str:
"""_summary_

Returns:
_type_: _description_
"""
careers_by_city = {}

for student in self.list_of_students:
city = student.city.title()
career = student.career.title()

if city not in careers_by_city:
careers_by_city[city] = set()

careers_by_city[city].add(career)

city_with_most_careers = None
max_quantity = 0

for city, careers in careers_by_city.items():
quantity = len(careers)
if quantity > max_quantity:
max_quantity = quantity
city_with_most_careers = city

return city_with_most_careers
106 changes: 106 additions & 0 deletions main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
from csv_management import CsvManagement

csv_management = CsvManagement('data.csv')

options = """
Opciones a consultar de la información del CSV de estudiantes!!!

1) Obtener todos los estudiantes que pertenezcan a una ciudad dada.
2) Obtener todos los estudiantes que vivan en un país dado.
3) Obtener todos los estudiantes que estén dentro del rango de edades
dado.
4) Obtener todas las ciudades de residencia de los estudiantes.
5) Identificar la edad promedio por carrera.
6) Indicar por carrera si el estudiante está por encima o por debajo del
promedio de edad.
7) Agrupa los estudiantes en diferentes rangos de edad (18-25, 26-35,
mayores de 35).
8) Identifica la ciudad que tienen la mayor variedad de carreras
universitarias entre los estudiantes.
9) Salir.
"""

value = None

while value is None or (1 <= value <= 9):
print(options)
option_entered = input("Ingresa una opción del 1 al 9: ")
try:
value = int(option_entered)

if value == 1:
city = input("Ingresa la ciudad: ")
students = csv_management.get_students_by_city(city)

if students:
print(
f'Los estudiantes de la ciudad de {city} son: {students}'
)
else:
print(f'No hay estudiantes asociados a {city}')

if value == 2:
country = input("Ingresa el pais: ")
students = csv_management.get_students_by_country(country)

if students:
print(
f'Los estudiantes que viven en {country} son: {students}'
)
else:
print(f'No hay estudiantes asociados a {country}')

if value == 3:
try:
min_age = int(input("Ingresa la edad minima: "))
max_age = int(input("Ingresa la edad maxima: "))

students = csv_management.get_students_by_age_range(
min_age,
max_age
)

if students:
print(
f'Los estudiantes entre {min_age} y {max_age} son: {students}'
)
else:
print('No hay estudiantes entre estas edades')

except ValueError:
print("Error: Debes ingresar un número válido.")

if value == 4:
cities = csv_management.get_cities()
print(f'Estas son las ciudades dode residen los estudiantes: {cities}')

if value == 5:
carrera = input("Ingresa carrera para calcular promedio edad: ")
average_age = csv_management.get_average_age_by_career(carrera)

if average_age != 0:
print(f'Para la carrera {carrera} el promedio es: {average_age}')

print(f'No se puede calcular el proedio para la carrera: {carrera}')

if value == 6:
student_name = input("Ingresa el nombre del estudiante: ")
student_is_above_or_below = csv_management.get_student_is_below_or_above_by_career_average_age(student_name)
print(f'{student_is_above_or_below}')

if value == 7:
groups_by_age = csv_management.sort_students_by_age()

for group, students in groups_by_age.items():
print(f'{group}: {students}')

if value == 8:
cities_with_careers = csv_management.get_city_with_most_careers()

print(f'La ciudad con mayor cantidad de carreras es: {cities_with_careers}')

if value == 9:
exit()

except ValueError:
print("Error: Debes ingresar un número válido.")
71 changes: 71 additions & 0 deletions poetry.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading