Skip to content

Commit fe7c955

Browse files
#22 - python
1 parent 3dc6075 commit fe7c955

File tree

1 file changed

+154
-0
lines changed

1 file changed

+154
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,154 @@
1+
#22 { Retos para Programadores } FUNCIONES DE ORDEN SUPERIOR
2+
3+
# Bibliography reference
4+
#Secrets of the JavaScript Ninja (John Resig, Bear Bibeault, Josip Maras) (z-lib.org)
5+
#Eloquent Javascript A Modern Introduction to Programming by Marijn Haverbeke (z-lib.org)
6+
#Python Notes for Professionals. 800+ pages of professional hints and tricks (GoalKicker.com) (Z-Library)
7+
# Additionally, I use GPT as a reference and sometimes to correct or generate proper comments.
8+
9+
"""
10+
* EJERCICIO:
11+
* Explora el concepto de funciones de orden superior en tu lenguaje
12+
* creando ejemplos simples (a tu elección) que muestren su funcionamiento.
13+
*
14+
* DIFICULTAD EXTRA (opcional):
15+
* Dada una lista de estudiantes (con sus nombres, fecha de nacimiento y
16+
* lista de calificaciones), utiliza funciones de orden superior para
17+
* realizar las siguientes operaciones de procesamiento y análisis:
18+
* - Promedio calificaciones: Obtiene una lista de estudiantes por nombre
19+
* y promedio de sus calificaciones.
20+
* - Mejores estudiantes: Obtiene una lista con el nombre de los estudiantes
21+
* que tienen calificaciones con un 9 o más de promedio.
22+
* - Nacimiento: Obtiene una lista de estudiantes ordenada desde el más joven.
23+
* - Mayor calificación: Obtiene la calificación más alta de entre todas las
24+
* de los alumnos.
25+
* - Una calificación debe estar comprendida entre 0 y 10 (admite decimales).
26+
27+
"""
28+
import random
29+
from datetime import datetime
30+
31+
log = print
32+
33+
log('Retos para Programadores #22')
34+
35+
# Higher-order function example: power function
36+
def powder(n):
37+
return lambda m: 1 if n == 0 else m * powder(n - 1)(m)
38+
39+
powder2 = powder(2)
40+
log(powder2(10)) # 100
41+
42+
# Higher-order function to apply a function to an array
43+
def apply_to_array(func):
44+
return lambda *arr: func(*arr)
45+
46+
def total_amount(*args):
47+
return sum(args)
48+
49+
sales = [123, 45, 67, 865, 76, 54, 3254, 23]
50+
log(apply_to_array(total_amount)(*sales)) # 4507
51+
52+
# Control flow function
53+
def unless(test, then):
54+
if not test:
55+
then()
56+
57+
def is_odd_num(n):
58+
return n % 2 != 0
59+
60+
# Higher-order function to add odd numbers up to n
61+
def add_odd_nums(n):
62+
total = 0
63+
while n > 0:
64+
if is_odd_num(n): # Check if n is odd
65+
total = add_to_total(n, total) # Update total
66+
n -= 1
67+
return total
68+
69+
# Helper function to add to total
70+
def add_to_total(n, total):
71+
return total + n
72+
73+
log(add_odd_nums(100)) # Should print 2500
74+
75+
76+
# EXTRA DIFFICULTY EXERCISE
77+
78+
# Student class definition
79+
class Student:
80+
def __init__(self, name, birthday, calification):
81+
self.name = name
82+
self.birthday = datetime.strptime(birthday, '%Y-%m-%d')
83+
self.calification = calification
84+
85+
def get_name(self):
86+
return self.name
87+
88+
def get_birthday(self):
89+
return self.birthday
90+
91+
def get_calification(self):
92+
return self.calification
93+
94+
def set_name(self, name):
95+
self.name = name
96+
97+
def set_birthday(self, birthday):
98+
self.birthday = datetime.strptime(birthday, '%Y-%m-%d')
99+
100+
def set_calification(self, calification):
101+
self.calification = calification
102+
103+
# List of students
104+
students = [
105+
Student('Juan Rulfo', '1986-06-07', 7),
106+
Student('Moure Dev', '1982-03-08', 8.5),
107+
Student('Calvin Maker', '2000-04-02', 9.8),
108+
Student('Adela Jimenez', '1976-01-09', 7.9),
109+
Student('Crist Renegate', '2001-07-09', 5),
110+
Student('Gautama Buda', '0623-05-23', 9),
111+
Student('Niko Zen', '1983-08-08', 10)
112+
]
113+
114+
# Function to get a list of students with their average grades
115+
def students_average_list(arr):
116+
return sorted(
117+
[{'name': student.get_name(), 'average': student.get_calification()} for student in arr],
118+
key=lambda x: x['average'],
119+
reverse=True
120+
)
121+
122+
# Function to get a list of students with grades of 9 or higher
123+
def higher_than_9_students(arr):
124+
return [student.get_name() for student in arr if student.get_calification() >= 9]
125+
126+
# Function to sort students by their birth date
127+
def sort_students_by_birthday(arr):
128+
return [student.get_name() for student in sorted(arr, key=lambda student: student.get_birthday())]
129+
130+
# Function to find the highest grade among all students
131+
def highest_calification(arr):
132+
return max(student.get_calification() for student in arr)
133+
134+
# Execute the functions and store the results
135+
average_list = students_average_list(students)
136+
best_students = higher_than_9_students(students)
137+
sorted_students = sort_students_by_birthday(students)
138+
highest_grade = highest_calification(students)
139+
140+
# Display the results in the console
141+
log("Average grades:", average_list)
142+
log("Best students (9 or higher):", best_students) # Best students (9 or higher): ['Calvin Maker', 'Gautama Buda', 'Niko Zen']
143+
log("Students sorted by birth date:", sorted_students) # Students sorted by birth date
144+
log("Highest grade:", highest_grade) # Highest grade: 10
145+
146+
# Output Example:
147+
"""
148+
Average grades: [{'name': 'Niko Zen', 'average': 10}, {'name': 'Calvin Maker', 'average': 9.8}, {'name': 'Gautama Buda', 'average': 9}, {'name': 'Moure Dev', 'average': 8.5}, {'name': 'Adela Jimenez', 'average': 7.9}, {'name': 'Juan Rulfo', 'average': 7}, {'name': 'Crist Renegate', 'average': 5}]
149+
Best students (9 or higher): ['Calvin Maker', 'Gautama Buda', 'Niko Zen']
150+
Students sorted by birth date: ['Gautama Buda', 'Adela Jimenez', 'Moure Dev', 'Niko Zen', 'Juan Rulfo', 'Calvin Maker', 'Crist Renegate']
151+
Highest grade: 10
152+
153+
"""
154+

0 commit comments

Comments
 (0)