Skip to content

Instantly share code, notes, and snippets.

@ricardosiri68
Last active August 29, 2015 14:22
Show Gist options
  • Select an option

  • Save ricardosiri68/723e69d8775bc7b58410 to your computer and use it in GitHub Desktop.

Select an option

Save ricardosiri68/723e69d8775bc7b58410 to your computer and use it in GitHub Desktop.
import os
import csv
from socios import Socios, SociosIngresados
def load_socios(filename, socios):
'''carga la lista de socios desde un fichero de extencion csv'''
with open(filename, 'rb') as csvfile:
socio_reader = csv.reader(csvfile, delimiter='|')
for socio in socio_reader:
socios.add(
numero=socio[0].strip(),
dni=socio[1].strip(),
nombre_apellido=socio[2].strip(),
fecha_nacimiento=socio[3].strip(),
fecha_afiliacion=socio[4].strip()
)
def clear_screen():
'''limpia la consola de comandos'''
# descomentar la siguente linea si usas linux
os.system('clear')
# o descomentar esta de abajo y comentar la de arriba si usas windows
# os.system('cls')
class MyCLI:
'''Interfaz de linea de comandos para operar las listas de socios que
ingresaron al estadio'''
def __init__(self):
self.__socios = Socios()
self.__ingresados = SociosIngresados(self.__socios)
load_socios(filename='socios.csv', socios=self.__socios)
def start(self):
while True:
self.show_main_menu()
def show_main_menu(self):
'''muestra el menu principal'''
clear_screen()
print "MENU PRINCIPAL"
print "1) Agregar Socio"
print "2) Ingresar Socio"
print "3) Listar Todos"
print "4) Listar Ingresados"
print "5) Ver Socio"
print "6) Listar Menores"
print "7) Listar Mayores"
print "8) Listar Activos"
print "9) Listar Antiguedades"
print "0) Salir"
option = raw_input(']> ')
try:
self.menu_options[option](self)
except KeyError:
self.main_menu_invalid_option()
def continuar(self):
raw_input('continuar...ENTER')
def main_menu_invalid_option(self):
raw_input('Opcion de menu Invalida!! ENTER/Continuar..')
def agregar_socio(self):
'''recibe las entradas para agregar un nuevo socio'''
pass
def ingresar_socio(self):
'''ingresa un socio al estadio segun su numero'''
pass
def view_socio(self):
'''obtiene la ficha de un socio segun su numero'''
pass
def listar_todos(self):
'''listar todos los socios afiliados'''
print 'NUMERO | DNI | NOMBRE | EDAD | ANTIGUEDAD | INGRESADO'
for socio in self.__socios:
print '{numero} | {dni} | {nombre} | {edad} | {antiguedad} | {ingreso}'.format(
numero=socio.numero,
dni=socio.dni,
nombre='{:<30}'.format(socio.nombre_apellido),
edad='{:<4}'.format(socio.edad),
antiguedad='{:<10}'.format(socio.anios_afiliado),
ingreso='SI' if socio in self.__ingresados.ingresados else 'NO'
)
self.continuar()
def listar_ingresados(self):
'''listar solo los socios que se encuentran en el estadio'''
pass
def listar_menores(self):
'''muestra la lista de socios menores'''
pass
def listar_mayores(self):
'''muestra la lista de socios mayores'''
pass
def listar_activos(self):
'''muestra la lista de socios activos'''
pass
def listar_antiguedades(self):
'''muestra conjuntos de cantidad de soscios agrupados por antiguedades
en orgen decendente'''
pass
def exit(self):
'''salir del programa'''
quit()
menu_options = {
'1': agregar_socio,
'2': ingresar_socio,
'3': listar_todos,
'4': listar_ingresados,
'5': view_socio,
'6': listar_menores,
'7': listar_mayores,
'8': listar_activos,
'9': listar_antiguedades,
'0': exit
}
if __name__ == '__main__':
cli = MyCLI()
cli.start()
import sys
import random
import time
def strTimeProp(start, end, format, prop):
'''start y end: establecen el rango de fechas
format: es el formato de I/O de la fecha
prop, es un aleatorio propuesto para la fecha'''
stime = time.mktime(time.strptime(start, format))
etime = time.mktime(time.strptime(end, format))
ptime = stime + prop * (etime - stime)
return time.strftime(format, time.localtime(ptime))
def randomDate(start, end, prop):
return strTimeProp(start, end, '%Y-%m-%d', prop)
for i in range(int(sys.argv[3])):
first_random = randomDate(
sys.argv[1],
sys.argv[2],
random.random()
)
second_random = randomDate(
first_random,
sys.argv[2],
random.random()
)
print "%s | %s" % (first_random, second_random)
import time
import math
class Socio(object):
fecha_format = '%Y-%m-%d'
def __init__(self,
numero=None,
dni='',
nombre_apellido='',
fecha_nacimiento=None,
fecha_afiliacion=None):
self.numero = numero
self.dni = dni
self.nombre_apellido = nombre_apellido
self.fecha_afiliacion = fecha_afiliacion
self.fecha_nacimiento = fecha_nacimiento
@property
def numero(self):
'''retorna el numero de afiliado'''
return self.__numero
@numero.setter
def numero(self, value):
'''define el numero de afiliado'''
self.__numero = value
@property
def dni(self):
'''retorna el DNI'''
return self.__dni
@dni.setter
def dni(self, value):
'''define el DNI'''
self.__dni = value
@property
def nombre_apellido(self):
'''retorna nombre y apellido'''
return self.__nombre_apellido
@nombre_apellido.setter
def nombre_apellido(self, value):
'''define nombre y apellido'''
self.__nombre_apellido = value
@property
def fecha_afiliacion(self):
'''retorna fecha de afiliacion en formato aaaa-mm-dd'''
return self.__fecha_afiliacion
@fecha_afiliacion.setter
def fecha_afiliacion(self, value):
'''define fecha de afiliacion en formato aaaa-mm-dd'''
self.__fecha_afiliacion = value
@property
def fecha_nacimiento(self):
'''retorna fecha de nacimiento en formato aaaa-mm-dd'''
return self.__fecha_nacimiento
@fecha_nacimiento.setter
def fecha_nacimiento(self, value):
'''define fecha de nacimiento en formato aaaa-mm-dd'''
self.__fecha_nacimiento = value
@property
def timestamp_afiliacion(self):
'''marca de tiempo de su afiliacion'''
return time.mktime(time.strptime(
self.__fecha_afiliacion,
self.fecha_format
))
@property
def timestamp_nacimiento(self):
'''marca de tiempo de su nacimiento'''
return time.mktime(time.strptime(
self.__fecha_nacimiento,
self.fecha_format
))
@property
def edad(self):
'''edad en anios (redondeado hacia abajo) desde que nacio'''
return int(math.floor(
(time.time() - self.timestamp_nacimiento) / # edad en segundos
(60 * 60 * 24 * 365) # segundos de un anio
))
@property
def anios_afiliado(self):
'''anios afiliado (redondeado hacia abajo) desde que se afilio'''
return int(math.floor(
(time.time() - self.timestamp_afiliacion) / # sefundos afiliado
(60 * 60 * 24 * 365) # segundos de un anio
))
We can make this file beautiful and searchable if this error is corrected: No commas found in this CSV file in line 0.
0001 | 31839905 | MARTIN MELO GALARZA | 2007-10-01 | 2008-12-21
0002 | 39887077 | AITOR AMARO IRIARTE | 2014-10-12 | 2014-12-09
0003 | 27072499 | ALEJANDRO PALOMAR MALO | 2014-11-12 | 2015-03-21
0004 | 41410890 | JOSE MARIA HIDALGO SALADO | 2013-09-08 | 2014-09-07
0005 | 33793303 | IGNACIO DEL HOYO ANTON | 1989-11-23 | 2007-03-20
0006 | 26484177 | DIEGO DIOS VALLES | 1989-06-29 | 1998-10-21
0007 | 37699036 | FELIPE DE LA CALLE MALLO | 2001-03-09 | 2003-03-08
0010 | 31301120 | GONZALO TORRENS CEDEÑO | 2003-01-17 | 2006-12-14
0011 | 40859075 | JOSE ANTONIO FRUTOS HIDALGO | 2008-07-08 | 2013-01-18
0012 | 20143790 | JOAQUIN TRONCOSO ESCAMILLA | 1993-04-30 | 2013-05-22
0013 | 24584670 | JOSEP MONEDERO ADRIAN | 1999-05-01 | 2000-01-18
0014 | 38850295 | IGNACIO SOTO GALLEGO | 2001-11-01 | 2005-10-12
0015 | 38463195 | PEDRO BUSTO PEÑARANDA | 1984-08-25 | 1992-03-14
0016 | 35874223 | ALBERT JUAREZ MAYORAL | 1993-02-07 | 2014-05-25
0017 | 32251551 | PABLO CENTENO VACA | 2009-03-22 | 2012-04-30
0020 | 30724758 | JOAQUIN POSADA FRANCISCO | 1992-06-02 | 1997-08-27
0021 | 32976030 | MARTIN VERDUGO OLEA | 2008-05-08 | 2011-10-13
0022 | 34271216 | NICOLAS CAMPO HERRERA | 2011-12-10 | 2014-03-16
0023 | 28226518 | DIEGO REQUEJO LLANOS | 1982-12-02 | 1987-04-21
0024 | 41298333 | SERGIO BUENDIA VIZUETE | 1987-03-13 | 1996-04-26
0025 | 27364978 | AGUSTIN HERREROS DOS SANTOS | 2006-10-15 | 2014-07-18
0026 | 38003985 | JUAN CALVET RAMON | 1984-05-24 | 2004-10-09
0027 | 34672284 | FELIPE GODOY LLUCH | 2003-10-17 | 2009-09-18
0030 | 37673782 | FERNANDO BRU CUETO | 2005-12-22 | 2008-12-11
0031 | 40045335 | SALVADOR VENEGAS HERNANDO | 2004-12-20 | 2008-05-02
0032 | 25906001 | NICOLAS CASTELLS PRADA | 2004-12-05 | 2007-09-16
0033 | 31111492 | AITOR CARRO VERGARA | 2009-10-01 | 2010-12-22
0034 | 30100185 | MARIANO POL MARMOL | 1998-09-24 | 2007-05-14
0035 | 38227091 | HECTOR PLANELLS FERRERO | 2013-05-16 | 2015-04-19
0036 | 24330134 | ALEJANDRO ARRIAGA SACRISTAN | 2009-12-07 | 2014-07-30
0037 | 27312067 | CAROLINE LITTLE | 1949-12-07 | 1950-12-27
0040 | 20156437 | MABLE MENDOZA | 1948-02-26 | 1948-05-25
0041 | 22938798 | GARRY SULLIVAN | 1950-09-14 | 1950-10-24
0042 | 31160900 | JUAN HOWARD | 1950-02-09 | 1950-03-26
0043 | 25737206 | BYRON PHELPS | 1950-04-24 | 1950-06-06
0044 | 30735138 | TRACI SANTOS | 1948-09-09 | 1950-09-19
0045 | 26971618 | GEORGE PRICE | 1951-09-30 | 1951-10-20
0046 | 27596151 | ETHEL HOLLOWAY | 1948-03-18 | 1950-12-19
0047 | 25646504 | JOYCE HINES | 1948-03-20 | 1949-09-20
0050 | 38993032 | TED WILLIS | 1948-01-20 | 1948-12-11
0051 | 27873610 | SHANE ELLIOTT | 1949-08-11 | 1950-10-17
0052 | 23100337 | APRIL MURRAY | 1950-11-13 | 1951-05-30
0053 | 34036087 | ROSIE STRICKLAND | 1951-08-05 | 1951-10-25
0054 | 22955576 | BRITTANY MILLS | 1951-11-15 | 1951-11-22
0055 | 22892413 | JEFF ROBERTS | 1948-05-05 | 1949-09-16
0056 | 38619343 | ROMAN FRANCIS | 1949-07-16 | 1950-08-12
0057 | 27663110 | KENT PATRICK | 1949-01-13 | 1949-05-19
0060 | 27626797 | HUBERT SUMMERS | 1951-08-06 | 1951-09-23
0061 | 38390117 | IGNACIO TUCKER | 1948-06-16 | 1949-04-03
0062 | 33959693 | KELLIE LEE | 1949-09-09 | 1949-12-10
0063 | 30055106 | LINDA HARRIS | 1950-09-18 | 1951-05-15
0064 | 37768494 | DANIELLE CORTEZ | 1948-09-20 | 1951-04-22
0065 | 24848053 | WILBUR PAUL | 1951-11-25 | 1951-12-27
0066 | 20053837 | ROBERTA PORTER | 1951-07-08 | 1951-08-26
0067 | 21059852 | TOMMY BROWN | 1951-10-13 | 1951-10-28
from socio import Socio
from socios_exceptions import (
SocioAlreadyExist,
SocioIsOutOfEstadium,
SocioAlreadyIngresado,
SocioDontExist
)
class Socios(list):
def add(self, **kwars):
'''agrega un socio a la lista si este aun no se encuentra'''
socio = Socio(**kwars)
try:
if self.get_by_numero(socio.numero):
raise SocioAlreadyExist(socio)
except SocioDontExist:
self.append(socio)
def get_by_numero(self, numero):
'''obtiene el socio segun su numero de asociado'''
for socio in self:
if socio.numero == numero:
return socio
raise SocioDontExist(numero)
def remove_by_numero(self, numero):
'''quita un socio de la lista segun su numero'''
socio = self.get_by_numero(numero)
if socio:
self.remove(socio)
return socio
class SociosIngresados:
def __init__(self, socios):
self.__socios = socios
self.__ingresados = []
@property
def socios(self):
'''lista completa de socios afiliados al club'''
return self.__socios
@property
def ingresados(self):
'''lista de socios afiliados que ingresaron al estadio'''
return self.__ingresados
def get_by_numero(self, numero):
'''obtiene un socio que ya ingreso segun su numero de socio'''
for socio in self.ingresados:
if socio.numero == numero:
return socio
raise SocioIsOutOfEstadium(numero)
def list_menores(self):
'''lista todos los socios que ingresaron y que son menores de 8
anios'''
for socio in self.ingresados:
if socio.edad < 8:
yield socio
def list_activos(self):
'''lista todos los socios que ingresaron y que tienen entre (8 - 60)
anios'''
for socio in self.ingresados:
if 8 <= socio.edad and 60 >= socio.edad:
yield socio
def list_mayores(self):
'''lista todos los socios que ingresaron y que son mayores de 60
anios'''
for socio in self.ingresados:
if socio.edad > 60:
yield socio
def dict_group_edad(self):
'''return un diccionario agrupando la edad como clave y cuantos de
edaad se encuentran como valor'''
edades = {}
for socio in self.ingresados:
if not socio.anios_afiliado in edades:
edades[socio.anios_afiliado] = 1
else:
edades[socio.anios_afiliado] += 1
return edades
def ingresar(self, numero):
'''registra un socio como ingresado segun su numero'''
socio = self.socios.get_by_numero(numero)
try:
if self.get_by_numero(numero):
raise SocioAlreadyIngresado(socio)
except SocioIsOutOfEstadium:
self.ingresados.append(socio)
class SocioAlreadyIngresado(Exception):
def __init__(self, socio):
message = 'El Socio {numero} - {nombre} ya se encuentra en el\
estadio'.format(numero=socio.numero, nombre=socio.nombre_apellido)
super(SocioAlreadyIngresado, self).__init__(message)
class SocioDontExist(Exception):
def __init__(self, numero):
message = 'El socio %s no se encuentra en la lista' % numero
super(SocioDontExist, self).__init__(message)
class SocioIsOutOfEstadium(Exception):
def __init__(self, numero):
message = 'El socio %s no se encuentra en el estadio' % numero
super(SocioIsOutOfEstadium, self).__init__(message)
class SocioAlreadyExist(Exception):
def __init__(self, socio):
message = 'El Socio {numero} - {nombre} ya se encuentra en la\
lista'.format(numero=socio.numero, nombre=socio.nombre_apellido)
super(SocioAlreadyExist, self).__init__(message)
import unittest
from socio import Socio
from socios import Socios, SociosIngresados
from molinete import load_socios
from socios_exceptions import (
SocioAlreadyExist,
SocioDontExist,
SocioIsOutOfEstadium,
SocioAlreadyIngresado
)
class TestSocio(unittest.TestCase):
def setUp(self):
self.socio = Socio(
numero='0001',
dni='31839905',
nombre_apellido='MARTIN MELO GALARZA',
fecha_nacimiento='2007-10-01',
fecha_afiliacion='2008-12-21'
)
def test_numero(self):
self.assertEqual('0001', self.socio.numero)
def test_nombre_apellido(self):
self.assertEqual('MARTIN MELO GALARZA', self.socio.nombre_apellido)
def test_dni(self):
self.assertEqual('31839905', self.socio.dni)
def test_fecha_afiliacion(self):
self.assertEqual('2008-12-21', self.socio.fecha_afiliacion)
def test_fecha_nacimiento(self):
self.assertEqual('2007-10-01', self.socio.fecha_nacimiento)
def test_timestamp_afiliado(self):
self.assertEqual(1229824800.0, self.socio.timestamp_afiliacion)
def test_timestamp_nacimiento(self):
self.assertEqual(1191207600.0, self.socio.timestamp_nacimiento)
def test_nacimiento_afiliacion(self):
self.assertLess(
self.socio.timestamp_nacimiento,
self.socio.timestamp_afiliacion
)
def test_edad(self):
self.assertEqual(7, self.socio.edad)
def test_anios_afiliado(self):
self.assertEqual(6, self.socio.anios_afiliado)
class TestSocios(unittest.TestCase):
def setUp(self):
self.socios = Socios()
load_socios('socios.csv', self.socios)
def test_length(self):
self.assertEqual(55, len(self.socios))
def test_get_one(self):
socio = self.socios.get_by_numero('0001')
self.assertEqual(self.socios[0], socio)
def test_get_wrong_one(self):
self.assertRaises(
SocioDontExist,
self.socios.get_by_numero,
'0008'
)
def test_add_existent(self):
self.assertRaises(
SocioAlreadyExist,
self.socios.add,
numero='0001',
dni='31839905',
nombre_apellido='MARTIN MELO GALARZA',
fecha_nacimiento='2007-10-01',
fecha_afiliacion='2008-12-21'
)
def test_remove_socio(self):
socio = self.socios.remove_by_numero('0001')
self.assertRaises(
ValueError,
self.socios.index,
socio
)
def test_remove_inexisting_socio(self):
self.assertRaises(
SocioDontExist,
self.socios.remove_by_numero,
'1111'
)
class TestSociosIngresados(unittest.TestCase):
def setUp(self):
socios = Socios()
self.socios = SociosIngresados(socios)
load_socios('socios.csv', socios)
for i in range(66):
num_socio = '%04d' % (i + 1)
try:
self.socios.ingresar(num_socio)
except:
pass
def test_get_one(self):
socio = self.socios.get_by_numero('0001')
self.assertEqual(self.socios.ingresados[0], socio)
def test_get_wrong_one(self):
del self.socios.ingresados[0]
self.assertRaises(
SocioIsOutOfEstadium,
self.socios.get_by_numero,
'0001'
)
def test_ingresar_existent(self):
self.assertRaises(
SocioAlreadyIngresado,
self.socios.ingresar,
'0001'
)
def test_list_menores(self):
control = ['0001', '0002', '0003', '0004', '0011', '0017', '0021',
'0022', '0033', '0035', '0036']
menores = [socio.numero for socio in self.socios.list_menores()]
self.assertEqual(control, menores)
def test_list_mayores(self):
control = ['0037', '0040', '0041', '0042', '0043', '0044', '0045',
'0046', '0047', '0050', '0051', '0052', '0053', '0054',
'0055', '0056', '0057', '0060', '0061', '0062', '0063',
'0064', '0065', '0066']
mayores = [socio.numero for socio in self.socios.list_mayores()]
self.assertEqual(control, mayores)
def test_list_activos(self):
control = ['0005', '0006', '0007', '0010', '0012', '0013', '0014',
'0015', '0016', '0020', '0023', '0024', '0025', '0026',
'0027', '0030', '0031', '0032', '0034']
activos = [socio.numero for socio in self.socios.list_activos()]
self.assertEqual(control, activos)
def test_list_all(self):
control = [
'%04d' % (i + 1) for i in range(66)
if not (i + 1) in (8, 9, 18, 19, 28, 29, 38, 39, 48, 49, 58, 59)
]
ingresados = [socio.numero for socio in self.socios.ingresados]
self.assertEqual(control, ingresados)
def test_grupo_antiguedad(self):
control = [(0, 6), (1, 2), (2, 2), (3, 2), (4, 1), (5, 1), (6, 2),
(7, 2), (8, 3), (9, 1), (10, 1), (12, 1), (15, 1), (16, 1),
(17, 1), (19, 1), (23, 1), (28, 1), (63, 6), (64, 9),
(65, 5), (66, 3), (67, 1)]
grupos_antiguedad = [
grupo for grupo in self.socios.dict_group_edad().items()
]
self.assertEqual(control, grupos_antiguedad)
if __name__ == '__main__':
unittest.main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment