Skip to content

Commit 9c560a6

Browse files
authored
Merge pull request mouredev#3997 from avcenal/main
#22 - Python
2 parents f67fe7c + 0d0c55f commit 9c560a6

File tree

1 file changed

+116
-0
lines changed
  • Roadmap/22 - FUNCIONES DE ORDEN SUPERIOR/python

1 file changed

+116
-0
lines changed
Lines changed: 116 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,116 @@
1+
"""
2+
EJERCICIO:
3+
* Explora el concepto de funciones de orden superior en tu lenguaje
4+
* creando ejemplos simples (a tu elección) que muestren su funcionamiento.
5+
"""
6+
def multiply_for_five(value:int):
7+
return value*5
8+
9+
def multiply_for_two(value:int):
10+
return value*2
11+
12+
def multiply_value(value,func):
13+
return func(value)
14+
15+
print(multiply_value(5,multiply_for_five))
16+
print(multiply_value(5,multiply_for_two)) #desde la misma función puedo llamar a otra
17+
print(multiply_value(5,lambda x:x*3)) #o incluso crear una lambda
18+
19+
#BUILT-IN HIGH ORDER LEVEL FUNCTIONS
20+
numbers = [1,2,3,4,5,6]
21+
print(list(map(lambda x:x*2,numbers)))
22+
print(list(filter(lambda x:x>3,numbers)))
23+
24+
#CLOSURES
25+
def sum_five(): #una función que retorna una función
26+
def add(value:int):
27+
return value + 5
28+
return add
29+
30+
print(sum_five()(7))
31+
32+
"""
33+
DIFICULTAD EXTRA (opcional):
34+
* Dada una lista de estudiantes (con sus nombres, fecha de nacimiento y
35+
* lista de calificaciones), utiliza funciones de orden superior para
36+
* realizar las siguientes operaciones de procesamiento y análisis:
37+
* - Promedio calificaciones: Obtiene una lista de estudiantes por nombre
38+
* y promedio de sus calificaciones.
39+
* - Mejores estudiantes: Obtiene una lista con el nombre de los estudiantes
40+
* que tienen calificaciones con un 9 o más de promedio.
41+
* - Nacimiento: Obtiene una lista de estudiantes ordenada desde el más joven.
42+
* - Mayor calificación: Obtiene la calificación más alta de entre todas las
43+
* de los alumnos.
44+
* - Una calificación debe estar comprendida entre 0 y 10 (admite decimales).
45+
"""
46+
47+
students = [
48+
{
49+
"name":"Alex",
50+
"birthdate" : "19/12/1984",
51+
"qualifications": [8.0,7.5,6.7,7.2]
52+
},
53+
{
54+
"name":"Sole",
55+
"birthdate" : "12/01/1983",
56+
"qualifications": [9.1,6.8,7.3,8.7]
57+
},
58+
{
59+
"name":"Martín",
60+
"birthdate" : "12/11/2015",
61+
"qualifications": [9.4,8.9,9.9,9.4]
62+
},
63+
{
64+
"name":"Valeria",
65+
"birthdate" : "17/04/2018",
66+
"qualifications": [9.0,8.9,9.7,9.1]
67+
}
68+
]
69+
70+
from functools import reduce
71+
from datetime import datetime
72+
from operator import itemgetter
73+
74+
def average(students:list): #BUILT-IN FUNCTION: REDUCE + LAMBDA
75+
result = []
76+
for student in students:
77+
qualifications_average = reduce(lambda x,y:x+y,student["qualifications"])/len(student["qualifications"])
78+
result.append({"name":student["name"],"average":round(qualifications_average,2)})
79+
return result
80+
81+
print(f"PROMEDIO DE CALIFICACIONES:\n{average(students)}")
82+
83+
84+
def best_students(students:list): #BUILT-IN FUNCTION: FILTER + LAMBDA
85+
students_with_average = average(students)
86+
bests = list(filter(lambda students_with_average: students_with_average["average"]>9,students_with_average))
87+
for student in bests:
88+
del(student["average"])
89+
return bests
90+
91+
print(f"\nMEJORES ALUMNOS:\n{best_students(students)}")
92+
93+
def sort_youngest(students:list): #CLOSURE
94+
def youngest ():
95+
sorted_students = list()
96+
for student in students:
97+
student["birthdate"] = datetime(day=int(student["birthdate"][0:2]),month=int(student["birthdate"][3:5]),year=int(student["birthdate"][6:])).timestamp()
98+
sorted_students = sorted(students,key=itemgetter("birthdate"),reverse=True)
99+
for student in sorted_students:
100+
student["birthdate"] = datetime.fromtimestamp(student["birthdate"]).strftime("%d/%m/%Y")
101+
return sorted_students
102+
return youngest
103+
104+
105+
print(f"\nALUMNOS ORDENADOS DESDE EL MÁS JOVEN:\n{sort_youngest(students)()}")
106+
107+
def find_best_student(students:list): #CLOSURE
108+
def best_qualifications():
109+
students_best_qualifications = list()
110+
for student in students:
111+
student["qualifications"] = sorted(student["qualifications"],reverse=True)
112+
students_best_qualifications.extend(student["qualifications"])
113+
return sorted(students_best_qualifications,reverse=True)[0]
114+
return best_qualifications
115+
116+
print(f"\nLA MEJOR NOTA:\n{find_best_student(students)()}")

0 commit comments

Comments
 (0)