¡Te damos la bienvenida a este reto!

1

Empezando con Python desde 0

Día 1

2

Variables, funciones y sintaxis básica

3

Tipos de datos: Numbers, Strings y Diccionarios

4

Playground - Retorna el tipo

Día 2

5

Operadores

6

Playground - Calcula la propina

Día 3

7

Condicionales

8

Playground - Averigua si un año es bisiesto

9

Ciclos

10

Playground - Dibuja un triangulo usando bucles

Día 4

11

Listas

12

Encuentra a los gatitos más famosos

13

Diccionarios

14

Obtén el promedio de los estudiantes

15

Tuplas

16

Obten la información de los paquetes

Día 5

17

Calcula la cantidad de letras en una oración

18

Encuentra el mayor palíndromo

Día 6

19

Sets

20

Encuentre la intersección de conjuntos

Día 7

21

List comprehension

22

Encuentra palabras con dos vocales

23

Dictionary Comprehension

24

Calcula la longitud de las palabras

Día 8

25

Funciones Lambda

26

Filtra mensajes de un user específico

27

Higher order functions

28

Crea tu propio método map

Día 9

29

Manejo de Errores y excepciones

30

Maneja correctamente los errores

31

Maneja las excepciones

Día 10

32

Playground - Crea un task manager usando closures

Día 11

33

Lectura de archivos de texto y CSV

Día 12

34

Programación orientada a objetos

35

Crea un auto usando clases

Día 13

36

Abstracción en Python

37

Playground - Crea un sistema de carrito de compras

38

Encapsulamiento en Python

39

Playground - Encapsula datos de los usuarios

Día 14

40

Herencia en Python

41

Playground - Jerarquía de animales usando herencia

Día 15

42

Polimorfismo en Python

43

Playground - Implementa un sistema de pagos

Día 16

44

Estructuras de datos en Python

45

Playground - Crea tu propia lista en python

46

Hash tables en Python

47

Playground - Implementación de una HashTable para Contactos

Día 17

48

Maps en Python

49

Playground - Crea un task manager con Maps

Día 18

50

Singly Linked List en Python

51

Playground - Implementación de una singly linked list

Día 19

52

Stacks en Python

53

Playground - Implementación de un stack

Día 20

54

Queues en Python

55

Playground - Implementación de una queue

Día 21

56

¡Lo lograste!

No tienes acceso a esta clase

¡Continúa aprendiendo! Únete y comienza a potenciar tu carrera

Obtén el promedio de los estudiantes

14/56

Aportes 68

Preguntas 2

Ordenar por:

¿Quieres ver más aportes, preguntas y respuestas de la comunidad?

muy bueno el reto, este y el anterior fueron verdaderos desafíos para mí, ahi es donde confirmo que de nada sirve ver los cursos sin una constante aplicación.

def get_student_average(students):
  classStudents = {"class_average" : 0, "students": []}
  averageClass = 0
  for i in students:
    student = {
        "name" : i["name"],
        "average" : round(sum(i["grades"])/len(i["grades"]), 2)
    }
    averageClass += student["average"]
    classStudents["students"].append(student)
  classStudents["class_average"] = round(averageClass/len(students), 2)
  return classStudents




get_student_average([
  {
    "name": "Pedro",
    "grades": [90, 87, 88, 90],
  },
  {
    "name": "Jose",
    "grades": [99, 71, 88, 96],
  },
  {
    "name": "Maria",
    "grades": [92, 81, 80, 96],
  },
])

Estuvo buenísimo este. Les comparto mi solución y la refactorización

.```
.
.
.
.
.
.
.
.
.
.


def get_student_average(students):
  #diccionario final
  newDict = {}
  #valores para el promedio general
  averageClass = []
  
  #agregar promedios individuales para calcular el promedio general
  for item in students:
    values = sum(item["grades"]) / len(item["grades"])
    averageClass.append(values)

  #generar el listado de estudiantes y promedios
  newStudentsDict = [{"name": item["name"], "average": round(sum(item["grades"]) / len(item["grades"]), 2)} for item in students]

  #modificar el diccionario final con valores 
  newDict["class_average"] = round(sum(averageClass) / len(averageClass),2)
  newDict["students"] = newStudentsDict

  return newDict

Refactor

def get_student_average(students):
  #promedio general
  promedio_general = round(sum(sum(student["grades"]) / len(student["grades"]) for student in students) / len(students), 2)
  
  #generar el listado de estudiantes y promedios
  newStudentsDict = [{"name": item["name"], "average": round(sum(item["grades"]) / len(item["grades"]), 2)} for item in students]


  return {"class_average": promedio_general, "students": newStudentsDict}
![]()![]()![]()![]()![]()![](https://static.platzi.com/media/user_upload/Captura%20de%20pantalla%202023-09-30%20135554-9088da64-1336-4e14-9887-27978a1135c9.jpg)
Qué emoción lo revisé le ajuste la parte en donde armaba la lista y paso la prueba, i'm very happy: ![](https://static.platzi.com/media/user_upload/image-5f6797e6-432d-418e-89dc-e3a8b5d872d4.jpg)
Reto cumplido. Muy bueno este reto. ![](https://static.platzi.com/media/user_upload/image-ea3bdf4e-30e0-46d8-b5fa-ec256731a18d.jpg) Desarrollo del reto. ```python def get_student_average(students): # Tu código aquí 👈 # Promedio por cada estudiante students_list = [] class_average = 0 # Halla el promedio por estudiante for student in students: prom_student = sum(student.get('grades')) / len(student.get('grades')) name = student.get('name') students_list.append({'name':name, 'average': round(prom_student, 2)}) class_average += prom_student # Halla el promedio de la clase class_average = round(class_average / len(students_list), 2) # Retorna diccionario return {'class_average': class_average, 'students': students_list} ```
Mi cara cuando consigo una solución perfectamente válida, limpia y sencilla pero el corrector automático me marca todo mal: [Imagen](https://pbs.twimg.com/media/FkjOQe5UUAAfOb_.jpg)
Estuvo entretenido y al parecer hay varias formas de resolverlo. ![](https://static.platzi.com/media/user_upload/image-579e9acd-f2c2-4696-8b42-fbde173175bb.jpg) . . . . . ```python def get_student_average(students): # Tu código aquí 👈 promedioEstudiantes = []; listaAlumnosYNotasPromedio = [] for estudiante in students: #Sacar los promedios de cada uno y almacenarlos en una lista. notasAlumno = estudiante["grades"] promedioEstudiante = round(sum(notasAlumno)/len(notasAlumno),2) #En un arreglo de diccionario y listas insertamos los datos almacenados. diccionarioAlumnosYNotasPromedio = {"name" : estudiante["name"], "average": promedioEstudiante} promedioEstudiantes.append(promedioEstudiante) listaAlumnosYNotasPromedio.append(diccionarioAlumnosYNotasPromedio) #Usar esa lista para sacar su promedio. Promedo de la clase. promedioClase = round(sum(promedioEstudiantes)/len(promedioEstudiantes),2) promedios = {"class_average": promedioClase, "students": listaAlumnosYNotasPromedio} return promedios ```
Completado el ejercicio, este fluyó un poco más fácil que el anterior, vamos mejorando... ![](https://static.platzi.com/media/user_upload/imagen-11aa057f-8fdf-4b68-baf3-fd2f11ba9d9f.jpg)
Hola, quiero compartir mi solución ```js def get_student_average(student_grades): result = { "class_average": 0, "students": [] } for index,student in enumerate(students_grades): result["students"].append({ "name": student["name"], "average": round(sum(students_grades[index]["grades"])/len(students_grades[index]["grades"]), 2) }) result["class_average"] = round(sum([student["average"] for student in result["students"]])/len(students_grades), 2) return result ```def get\_student\_average(student\_grades): result = { "class\_average": 0, "students": \[] } for index,student in enumerate(students\_grades): result\["students"].append({ "name": student\["name"], "average": round(sum(students\_grades\[index]\["grades"])/len(students\_grades\[index]\["grades"]), 2) }) result\["class\_average"] = round(sum(\[student\["average"] for student in result\["students"]])/len(students\_grades), 2) return result
```js def get_student_average(students): # Tu código aquí 👈 names = [] averages = [] students_list = [] for s in students: name = s["name"] names.append(name) grades = s["grades"] average = sum(grades)/len(grades) averages.append(average) class_average = round(sum(averages)/len(averages),2) for name, average in zip(names,averages): student = { "name": name, "average": average } students_list.append(student) class_students = { "class_average": class_average, "students": students_list } print(class_students) pass ```def get\_student\_average(students):  # Tu código aquí 👈  names = \[]  averages = \[]  students\_list = \[]  for s in students:    name = s\["name"]    names.append(name)    grades = s\["grades"]    average = sum(grades)/len(grades)    averages.append(average)    class\_average = round(sum(averages)/len(averages),2)    for name, average in zip(names,averages):    student = {      "name": name,      "average": average    }    students\_list.append(student)    class\_students = {    "class\_average": class\_average,    "students": students\_list  }  print(class\_students)  pass
```js def get_student_average(students): # Tu código aquí 👈 new_dicc={} promedios=[] acumulador_de_promedios: float = 0 cuenta_estudiantes=0 for estudiante in students: cuenta_estudiantes += 1 acumulador_de_notas: float=0 cuenta_notas=0 for notas in estudiante["grades"]: acumulador_de_notas += notas cuenta_notas += 1 new_dicc["name"]=estudiante["name"] new_dicc["average"]=round(acumulador_de_notas/cuenta_notas,2) promedios.append(new_dicc) acumulador_de_promedios += new_dicc["average"] new_dicc={} dicc_salida={} dicc_salida["class_average"]=round(acumulador_de_promedios/cuenta_estudiantes,2) dicc_salida["students"]=promedios return dicc_salida ```
Mi solucion: def get\_student\_average(students):    ltotalstudens      = \[]    ltotalstudens.clear    dstudens           = {}    dtotalstudens      = {}    class\_average      = 0    for element01 in students:               dstudens\['name']         = element01\["name"]        dstudens\['average']      = (round(sum(element01\["grades"]) / len(element01\["grades"]),2))                class\_average            = class\_average + dstudens\['average']        ltotalstudens.append({dstudens\['name'], dstudens\['average']})    dtotalstudens\['class\_average'] = round(class\_average/len(ltotalstudens),2)    dtotalstudens\['students']      = ltotalstudens    return dtotalstudens    if \_\_name\_\_  == '\_\_main\_\_':    students=\[        {            "name": "Pedro",            "grades": \[90, 87, 88, 90],        },        {            "name": "Jose",            "grades": \[99, 71, 88, 96],        },        {            "name": "Maria",            "grades": \[92, 81, 80, 96],        },        ]    result=get\_student\_average(students)    print(result)


⬇️

⬇️

⬇️

def get_student_average(students):
  studentp = []
  class_average = {}
  sum_prom = 0
  d = {}
  for dic in students:
    #print(round((sum(dic["grades"])/len(dic["grades"])),2))
    #std[dic["name"]] = round((sum(dic["grades"])/len(dic["grades"])),2)
    sum_prom = sum_prom + (round((sum(dic["grades"])/len(dic["grades"])),2))
    studentp.append({"name":dic["name"]  , "average" : round((sum(dic["grades"])/len(dic["grades"])),2)  } )
  d["class_average" ] = (round(sum_prom /len(studentp),2))
  # print (d)
  # print(studentp)
  d["students"] = studentp
  print (d)
  return d

mi humilde aporte me corre en vscode…
def get_student_average(students):
salida = {}
total_class = {}
famous_student = []
average = 0.00
total_average = 0.00
for x in students:
name = x[‘name’]
average = round(sum(x[‘grades’]) / len(x[‘grades’]), 2)
total_average = total_average + average
salida[name] = average

famous_student.append(salida) 
total_class["class_average"] = round(total_average/len(salida),2)
total_class["students"]      = famous_student
print(total_class)

Input: get_student_average([
{
“name”: “Pedro”,
“grades”: [90, 87, 88, 90],
},
{
“name”: “Jose”,
“grades”: [99, 71, 88, 96],
},
{
“name”: “Maria”,
“grades”: [92, 81, 80, 96],
},
])

Comparto mi aporte

.
.
.
.
.
.
.
.
.
.

<code> 
def get_student_average(students):
  # print(students)
  finalaveragedict = { "class_average": 0, "students":[] }
  classaveragesum = 0
  classaveragecount = 0
  
  for student in students:
     gradessum = sum(student['grades'])
     gradeslength = len(student['grades'])
     average =  round(gradessum/gradeslength, 2)
     finalaveragedict['students'].append({'name' : student['name'],'average' : average})
     classaveragesum += average
     classaveragecount += 1
     
     if len(students) == classaveragecount:
         finalaveragedict['class_average'] = round(classaveragesum/classaveragecount, 2)
         
  return finalaveragedict
def get_student_average(students):
  rta= {"class_average" : 0, "students": []}
  promedios = []

  for student in students:
    student["grades"] = sum(student["grades"])/len(student["grades"]) 

    promedios.append(student["grades"])

    rta["students"].append({
        "name": student["name"],
        "average": round(student["grades"],2)
      })

  rta["class_average"] = round(sum(promedios)/len(students),2 ) 
  return(rta)

🛡️🛡️Escudo anti-spoilers🛡️🛡️

Mi solución al reto:

def get_student_average(students):
  result = dict({
    "class_average": 0.0,
    "students": list()
  })
  average = 0.0 
  for student in students:
    student_average = round(sum(student['grades']) / len(student['grades']), 2)
    result['students'].append(
    {
      "name" : student['name'],
      "average": student_average
    })
    average += student_average
  result['class_average'] = round(average / len(students), 2)
  return result 


.
.
.
.
.
.
.
.
.
.

Mi código:

def get_student_average(students):
    # Calculamos el promedio individual de cada estudiante
    for student in students:
        average = sum(student["grades"]) / len(student["grades"])
        student["average"] = round(average, 2)
        # Eliminamos la clave "grades" para el formato de salida
        del student["grades"]
    
    # Calculamos el promedio de la clase
    class_average = sum(student["average"] for student in students) / len(students)
    class_average = round(class_average, 2)
    
    # Creamos el diccionario de salida
    output = {
        "class_average": class_average,
        "students": students
    }
    
    return output

def get_student_average(students):
average_total = 0
for student in students:
student.update({“average”: round(sum(student[‘grades’])/len(student[‘grades’]),2) })
average_total += student[‘average’]
average_total = round(average_total/len(students),2)

for student in students:
student.pop(‘grades’)

return {‘class_average’: average_total, ‘students’: students}

**
*
*
*
*
*
*
*
**
*
*
*
*
*
*
*
**
*
*
*
*
*
*
*
*

def get_student_average(students):
  res = dict(class_average=0, students=[])
  for student in students:
    grades = student.get('grades')
    average = sum(grades) / len(grades)
    res.get('students').append(dict(name=student.get('name'), average=round(average, 2)))
    res['class_average'] += average
  res['class_average'] = round(res['class_average'] / len(students), 2)
  return res

Da la solución pero no pasa ningún test jajaj



def get_student_average(students):
  
  rta = {
    "class_average": 0,
    "students": []
  }
  
  for x in students:
    
    c=round(sum(x["grades"])/len(x["grades"]),2)
    rta["class_average"]+= c
    
    rta["students"].append({
      "name": x["name"],
      "average": c
    })
    
  rta["class_average"]=round((rta["class_average"]/len(students)),2)

  
  print (rta)
  
  
  pass


get_student_average([
   {
    "name": "Pedro",
    "grades": [90, 87, 88, 90],
  },
  {
    "name": "Jose",
    "grades": [99, 71, 88, 96],
  },
  {
    "name": "Maria",
    "grades": [92, 81, 80, 96],
  },
])

Listo!

Estudiantes = [{
“Alumno”: “Billy”,
“Notas”: [5.0, 4.5, 4.2, 4.6]
},
{
“Alumno”: “John”,
“Notas”: [4.0, 2.5, 3.2, 5.0]
},
{
“Alumno”: “May”,
“Notas”: [5.0, 4.7, 5.0, 4.8]
},
{
“Alumno”: “Valentina”,
“Notas”: [4.0, 3.8, 5.0, 4.8]
},
{
“Alumno”: “Andres”,
“Notas”: [4.5, 3.9, 4.0, 4.2]
},
{
“Alumno”: “Valeria”,
“Notas”: [2.0, 3.5, 4.0, 3.0]
},
{
“Alumno”: “Andrea”,
“Notas”: [4.7, 4.8, 5.0, 4.3]
},
{
“Alumno”: “Diana”,
“Notas”: [5.0, 4.8, 5.0, 4.9]
},
{
“Alumno”: “Lulla”,
“Notas”: [5.0, 4.8, 5.0, 4.8]
},
{
“Alumno”: “Juan Pablo”,
“Notas”: [4.5, 3.7, 4.6, 3.9]
}]
def Promedio(Estudiantes):
i=0
Alumno = []
Notas = []
for Estudiante in Estudiantes:
Alumno.append(Estudiante[“Alumno”])
Notas.append(sum(Estudiante[“Notas”])/4)
print(f" El estudiante {Alumno[i]} obtuvo un promedio de {Notas[i]}")
i+=1
T = sum(Notas)/10
print (f"El promedio Total de todos los estudiantes es de {T}")
Promedio(Estudiantes)

def get_student_average(students):
  """Function Get Student Average"""
  
  # Inicio variable para el promedio del salón
  average_general = 0

  # Inicio dictionario a retornar
  average_list = {
      "class_average": 0,
      "students": [],
  }

  # Bucle to iterar the listy and get the dict to iterar 
  for item in students:
    average = 0

    # Bucle for Iterar el dict and get the student average
    for value in item["grades"]:
      average += value

    # Calcule the student average
    average_student = average / len(item["grades"])
    average_student = round(average_student, 2)

    # Add to dict the student and average round with .00
    average_list["students"].append({
        "name": item["name"],
        "average": average_student
    })
    # average_list["students"] = {"name": item["name"], "average": average_student}

    # Calcule the general average
    average_general += average_student

  average_general = average_general / len(students)
  average_general = round(average_general, 2)

  # Add to dict the general average
  average_list["class_average"] = average_general

  # Return the dict with the general and student average
  return average_list


students = [
    {
        'name': 'Pedro',
        'grades': [90, 87, 88, 90],
    },
    {
        "name": "Jose",
        "grades": [99, 71, 88, 96],
    },
    {
        "name": "Maria",
        "grades": [92, 81, 80, 96],
    },
]

student_average = get_student_average(students)
print(student_average)

resultado:

solución:

""""
Programa para calcular el promedio individual de cada estudiante 
"""
def get_student_average(students):
    ##creando la lista de studiantes
    liststudents=[]
    listaverage=[]
    ## creando el diccionario
    dictresultfinal={ 
        "class_average": 0,
        "students": []
    }
    #extraermos la suma
    for prop in students:
        averagetemp=0 
        sumagradestemp=sum(prop['grades'])
        mountgradestemp=len(prop['grades'])
        averagetemp=round(sumagradestemp/mountgradestemp,2)
        listaverage.append(averagetemp)
        #agregar a lista de studiantes
        liststudents.append({'name': prop['name'], 'average': averagetemp})

    averagesum=sum(listaverage)
    mountaverages=len(listaverage) 
    averagefinal=round((averagesum/mountaverages), 2)

    # Agregando al diccionario
    dictresultfinal={'class_average':averagefinal, 'students': liststudents}
    return dictresultfinal

if __name__ == '__main__':
  response=get_student_average([
  {
    "name": "Pedro",
    "grades": [90, 87, 88, 90],
  },
  {
    "name": "Jose",
    "grades": [99, 71, 88, 96],
  },
  {
    "name": "Maria",
    "grades": [92, 81, 80, 96],
  },])
  print(response)
def get_student_average(students):
    group = []
    students_grades = []

    for student in students:
        student["grades"] = round(sum(student["grades"]) / len(student["grades"]), 2)
        group.append(student["grades"])

    for student in students:
        students_grades.append({"name": student["name"], "average": student["grades"]})

    return {
        "class_average": round(sum(group) / len(group), 2),
        "students": students_grades,
    }

Solución 😄…
.

.
.
.
.

def get_student_average(students):
  students_averages = [{
    "name": student["name"],
    "average": round(sum(
    student["grades"]) / len(student["grades"]
    ), 2)}
  for student in students
  ]

  class_average = round(sum(
    student["average"]
    for student in students_averages
    ) / len(students_averages), 2)
  
  return {
  "class_average": class_average,
  "students": students_averages
}

Mi humilde aporte

student_class = [
  {
    "name": "Pedro",
    "grades": [90, 87, 88, 90],
  },
  {
    "name": "Jose",
    "grades": [99, 71, 88, 96],
  },
  {
    "name": "Maria",
    "grades": [92, 81, 80, 96],
  }
]

def get_student_average(students):
  # Tu código aquí 👈
  prom_total = 0
  prom_ind = 0
  dict_final = {}
  list_students = []
  for student in students:
    dict_students = {}
    prom_total += (sum(student['grades']) / len(student['grades']))
    prom_ind = sum(student['grades']) / len(student['grades'])
    dict_students['name'] = student['name']
    dict_students['average'] = round(prom_ind, 2)
    list_students.append(dict_students)
    del dict_students

  class_average = prom_total / len(students)
  dict_final['class_average'] = round(class_average, 2)
  dict_final['students'] = list_students

  return dict_final

new_dict = get_student_average(student_class)
print(new_dict)
def get_student_average(students):
  # Tu código aquí 👈
  
  prom_curso = 0
  new_students = []

  # curso = [
  #   {
  #     "name": "Pedro",
  #     "grades": [90, 87, 88, 90],
  #   },
  #   {
  #     "name": "Jose",
  #     "grades": [99, 71, 88, 96],
  #   },
  #   {
  #     "name": "Maria",
  #     "grades": [92, 81, 80, 96],
  #   },
  # ]

  for i in students:
    #print(i["grades"])
    total_estudiante = 0

    for j in i["grades"]:
      total_estudiante = total_estudiante + j
    #print(i["name"])
    prom_estudiante = total_estudiante / len(i["grades"])
    prom_estudiante = round(prom_estudiante, 2)
    prom_curso = prom_curso + prom_estudiante

    #print("total_estudiante = " + str(total_estudiante))
    #print("prom_estudiante = " + str(prom_estudiante))
    new_students.append({"name":i["name"], "average":prom_estudiante})

  prom_curso = prom_curso / len(students)
  #print(len(curso))
  prom_curso = round(prom_curso, 2)
  #print("prom_curso = " + str(prom_curso))  
  #print(students)
  new_curso = {"class_average":prom_curso, "students":new_students}
  return new_curso

dict =  get_student_average([
  {
    "name": "Pedro",
    "grades": [90, 87, 88, 90],
  },
  {
    "name": "Jose",
    "grades": [99, 71, 88, 96],
  },
  {
    "name": "Maria",
    "grades": [92, 81, 80, 96],
  },
])

print(dict)
def get_student_average(students):

  list_students = []
  total_average = 0

  for i in students:
    x = list(i.values())

    student = {
      'name': x[0],
      'average': round(sum(x[1])/len(x[1]),2)
    }

    total_average += sum(x[1])/len(x[1])
    list_students.append(student)

  total_average = round(total_average/len(list_students),2)

  student_average = {
    "class_average": total_average,
    "students": list_students
  }

  return student_average

Una recomendacion para este tipo de retos es revisar bien la identacion, solo por omitir esto el resultado me dio 8.16, lo suficiente para ser despreciado pero no lo suficiente para pasar el test.


.
.

MI aporte

def get_student_average(salon):

  p1 = {}
  s1 = []
  aux3 = 0
  for elemento in salon:
     s1.append({"name":elemento['name'],"average":round(sum(elemento['grades'])/len(elemento['grades']),2)})
     aux3 += sum(elemento['grades'])/len(elemento['grades'])
  
  return {"class_average": round(aux3/len(s1),2),
      "students": s1}
def get_student_average(students):
    student_average = [round(sum(student['grades'])/len(student['grades']), 2) for student in students]
    class_average = round(sum(student_average) / len(student_average), 2)
    
    lst_students = [{
            "name": student['name'],
            "average": grade
            } 
            for student, grade in zip(students, student_average)]
    
    output = {
        "class_average": class_average,
        "students": lst_students
    }

    return output

Acá la solución, agregué typing para así mostrar buenas prácticas en código:
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

from typing import List

def get_student_average(students: List[dict]) -> dict:
  # Tu código aquí 👈
  class_total: int = 0
  students_list: list = []

  for student in students:
    name: str = student["name"]
    grades: List[int] = student["grades"]
    average: float = round(sum(grades) / len(grades), 2)
    students_list.append({"name": name, "average": average})
    class_total += average

  class_average: float = round(class_total / len(students), 2)
  return {"class_average": class_average, "students": students_list}

Mi solución:
.
.
.
.
.
.
.
.
.

def get_student_average(students):
  
  students_list= [{"name":student["name"], "average":round((sum(student["grades"])/(len(student["grades"]))),2)} for student in students]
  
  class_average = round(sum([sum(student["grades"])/(len(student["grades"]))/(len(students)) for student in students]),2)
  
  return {
    "class_average":class_average,
    "students": students_list
  }

Comparto mi solución:
.

.
.
.
.
.

def get_student_average(students):
  average = {
    "class_average": 0,
    "students": []
    }
  for student in students:
    average["students"].append(dict([
      ("name", student["name"]),
      ("average", round(sum(student["grades"])/len(student["grades"]), 2))
      ]))
    average["class_average"] += average["students"][-1]["average"]
    
  average["class_average"] /= len(average["students"])
  average["class_average"] = round(average["class_average"], 2)

  return average

Aqui mi resultado:
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

def get_student_average(students):
  # Tu código aquí 👈
  classAverage = 0
  studentsAverage = []
  for student in students:
    sumGrades = 0
    for grade in student['grades']:
      sumGrades += grade
    average = round(sumGrades / len(student['grades']), 2)
    studentsAverage.append({
      'name': student['name'],
      'average': average
    })
    classAverage += average
  classAverage = round(classAverage / len(students), 2)
  return {
    'class_average': classAverage,
    'students': studentsAverage
  }
  pass

Dejo dos soluciones que se me ocurrieron:
La primera utilizando la func ‘mean’ del módulo ‘statistics’ que nos da el promedio de un iterable. Y la segunda utilizando las built-in funcs ‘sum’ y ‘len’ para calcular el promedio.
.
.
.
.
.
.
.
.
.
.

from statistics import mean

def get_student_average(students: list[dict]) -> dict:
    new_dict = {}
    new_dict["class_average"] = []
    for s in students:
        s["average"] = round(mean(s["grades"]), 2)
        s.pop("grades")
        new_dict["class_average"].append(s["average"])
    new_dict["students"] = students.copy()
    new_dict["class_average"] = round(mean(new_dict["class_average"]), 2)

    return new_dict

def get_student_average_large(students: list[dict]) -> dict:
    new_dict = {}
    new_dict["class_average"] = []
    for s in students:
        s["average"] = round(sum(s["grades"]) / len(s["grades"]), 2)
        s.pop("grades")
        new_dict["class_average"].append(s["average"])
    new_dict["students"] = students.copy()
    new_dict["class_average"] = round(sum(new_dict["class_average"])/ len(new_dict["class_average"]), 2)

    return new_dict


Los retos en Python son más fáciles de resolver que con los de JavaScript, debe ser porque Python es un lenguaje más sencillo, aquí mi solución:

def get_student_average(students):
  sum_students_averages = 0
  averages = {
    "class_average":0,
    "students":[]
  }
  for i in students:
    student_average = {
      "name": i["name"],
      "average": round(sum(i["grades"])/len(i["grades"]),2)
    }
    averages["students"].append(student_average)
    sum_students_averages+=student_average["average"]
  averages["class_average"]=round(sum_students_averages/len(students),2)
  return averages
def get_student_average(students):

    class_average = 0
    students_list = []
    
    for student in students:
        student_name = student["name"]
        student_grades = student["grades"]
        student_average = sum(student_grades) / len(student_grades)
        student_average = round(student_average, 2)
    
        class_average += student_average
    
        students_list.append({
        "name": student_name,
        "average": student_average,
        })
    
    class_average = class_average / len(students)
    class_average = round(class_average, 2)
    
    return {
        "class_average": class_average,
        "students": students_list,
    }
    pass


.
.
.
.
.
.

def get_student_average(students):
  # Tu código aquí 👈
    class_total = 0
    student_list = []
    
    for student in students:
        name = student['name']
        grades = student['grades']
        average = sum(grades) / len(grades)
        class_total += average
        student_list.append({"name": name, "average": round(average, 2)})
    
    class_average = class_total / len(students)
    class_average = round(class_average, 2)
    
    return {"class_average": class_average, "students": student_list}

Mi solución:
.
.
.
.
.
.
.
.

def get_student_average(students):
  students = [{"name": student["name"], "average": round(sum(student["grades"])/len(student["grades"]),2)} for student in students]
  class_average = round(sum(student["average"]/len(students) for student in students), 2)
  return {"class_average": class_average, "students": students}

"





‘’

’’

‘’


‘’’





’’

def get_student_average(students):
  # Claculo el numero de estudiantes, incio class averange y la lista vacia de promedio de estudiante
  total_students = len(students)
  sum_average = 0
  average_list= []  # sum_average / total_students
  # itero cada elemento la lista de estudiantes para sacar el promedio por estudiate
  for student in students:
    average_student = sum(student["grades"]) / len(student["grades"])
    sum_average = sum_average + average_student
    average_list.append({
      "name":student["name"],
      "average":average_student
    })
  if total_students > 0:
    class_average = sum_average / total_students
    class_average = round(class_average, 2)
  else:
    class_average = 0
    
  # Regreso el diccionario con le promedio total y los promedio individuales
  return  {
    "class_average": class_average,
    "students":average_list
  }


students = [
  {
    "name": "Pedro",
    "grades": [90, 87, 88, 90],
  },
  {
    "name": "Jose",
    "grades": [99, 71, 88, 96],
  },
  {
    "name": "Maria",
    "grades": [92, 81, 80, 96],
  },
]
resultado = get_student_average(students)
print(resultado)


.
.
.
.
.
.
.

def get_student_average(students):
  avg = 0

  for i in students:
    avg += sum(i['grades']) / len(i['grades'])
    i['grades'] = round(avg, 2)
  class_avg = avg / len(students)
  students.insert(0, {"class_average": round(class_avg, 2)})

students = [
  {
    "name": "Pedro",
    "grades": [90, 87, 88, 90],
  },
  {
    "name": "Jose",
    "grades": [99, 71, 88, 96],
  },
  {
    "name": "Maria",
    "grades": [92, 81, 80, 96],
  }
]

get_student_average(students)
print(students)

Mi solución, claro con un poco de ayuda, pero no pasó las pruebas, no se si sea porque no estoy usando la variable response o sigue con bug la página


.
.
.
Por fin entendí mejorcomo iterar 🐍👌🏼
.
.
.
.

def get_student_average(students):
  #variables
  respuesta= {"class_average":0,"students":[]}
  sumaCalificaciones = 0
  #iterando
  for element in students:
    estudiante = {"name" : element["name"], "average":round(sum(element["grades"])/len(element["grades"]), 2)}
    
    sumaCalificaciones += estudiante["average"]
    
    respuesta["students"].append(estudiante)

  #promedio de la clase
  respuesta["class_average"] = round(sumaCalificaciones/len(students), 2)

  return respuesta


.
.
.
.
.
.
.
.
.

def get_student_average(students):
	classInfo = {
		'class_average': 0,
		'students': []
	}
	classAverage = 0	

	for student in students:
		average = sum(student['grades']) / len(student['grades'])
		classInfo['students'].append({ 'name': student['name'], 'average': round(average, 2)})
		classAverage += average

	classInfo['class_average'] = round(classAverage / len(students), 2)

	return classInfo
def get_student_average(students):
  # Crear la estructura del objeto
  class_average = {
    "class_average": 0,
    "students": [
      {
        "name": "",
        "average": 0
      }
    ]
  }

  # Reiniciar el array de `students`
  class_average["students"] = []
  general_avg = 0

  for student in students:
    # Obtener la suma de todas las notas por estudiante
    sum_grades = sum(student["grades"])

    # Calcular el promedio por cada estudiante
    avg = sum_grades / len(student["grades"])

    # Guardar los datos en el objeto
    class_average["students"].append({
      "name": student["name"],
      "average": round(avg, 2)
    })

    # Sumar los promedios de los estudiantes
    general_avg += class_average["students"][-1]["average"]

  # Calcular el promedio general
  general_avg = general_avg / len(students)
  class_average["class_average"] = round(general_avg, 2)

  return class_average


*
*
*
*
*
*
*
*
*

def get_student_average(students):
  prom_clase=[]
  estudiantes=[]
  
  for element in students:
    prom_estud=round((sum(element.get("grades")))/len(element.get("grades")),2) # promedio por estudiante
    prom_clase.append(prom_estud) #lista con los promedios de los estudiantes
    estudiantes.append({"name":element.get("name"),"average":prom_estud}) # lista de diccionarios por estudiante
  promedio=(round(sum(prom_clase)/(len(prom_clase)),2) # promedio de la clase
  clase={"class_average":promedio,"students":estudiantes } #diccionario final
  return clase

Espero les sirva.

Mi aporte

.
.
.
.
.

def get_student_average(students):
  
  SumNota = 0
  i = 0
  listaestudiante=[]
  cant_est = 0
  Sumnotacurso = 0
  
  for datos_estudiante in  students:
      cant_est += 1
      SumNota = 0
      i = 0
      
      for nota in datos_estudiante['grades']:
          SumNota += nota
          i += 1
      
      promedio_estudiante = round(SumNota / i,2)
      
      diccestudiantepromedio = {'name':datos_estudiante['name'],
                                'average':promedio_estudiante}
      listaestudiante.append(diccestudiantepromedio)
      
      Sumnotacurso += promedio_estudiante
  
  promedio_curso = round(Sumnotacurso / cant_est,2)
  
  resultados = {'class_average':promedio_curso,
                'students':listaestudiante
                }
  print(listaestudiante)
  print(promedio_curso)
  return  resultados  
  pass


promedios = get_student_average([
  {
    "name": "Pedro",
    "grades": [90, 87, 88, 90],
  },
  {
    "name": "Jose",
    "grades": [99, 71, 88, 96],
  },
  {
    "name": "Maria",
    "grades": [92, 81, 80, 96],
  }
  ])
print(promedios)

Mi solución:

def get_student_average(students):

  output = {"students":[]}
  class_average = []

  for student in students:

    grades = sum(student['grades'])/len(student['grades'])
    class_average.append(round(grades, 2))
    average = sum(class_average)/len(class_average)
    
    output["students"].append(
      {
        'name': student['name'],
        'average': grades
      }
    )

    output["class_average"] = round(average,2)

  return output

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

def get_student_average(students):
  student_rta=[]
  average=[]
  for student in students:
    avg=calculate_average(student["grades"])
    student_rta.append({
      "name": student["name"],
      "average": avg
    })
    average.append(avg)
  salon_resume={
      "class_average":calculate_average(average),
      "students": student_rta
  }

  return salon_resume

def calculate_average(califications: list):
  acum=0
  for calification in califications:
    acum+=calification
  
  return round((acum / len(califications)),2)



student1 = [
  {
    "name": "Pedro",
    "grades": [90, 87, 88, 90],
  },
  {
    "name": "Jose",
    "grades": [99, 71, 88, 96],
  },
  {
    "name": "Maria",
    "grades": [92, 81, 80, 96],
  },
]

print (get_student_average(student1))

Mi aporte 😄

def get_student_average(students):
  results = {
    "class_average":0,
    "students":[]
  }
  class_avg=0
  for student in students:
    student_average=round(sum(student['grades'])/len(student['grades']),2)
    class_avg+=student_average
    studentResults={"name":student['name'],"average":student_average}
    results['students'].append(studentResults)
  results['class_average']=round(class_avg/len(students),2)
  return results


Despues de muchos intentos, finalmente se pudo!

def get_student_average(students):
  averages = [
    round(sum(s['grades']) / len(s['grades']), 2)
    for s in students
  ]
  average = round(sum(averages) / len(averages), 2)
  names = [s['name'] for s in students]
  names_averages = [
    {'name': name, 'average': grade}
    for name, grade in zip(names, averages)
  ]
  return {
    'class_average': average,
    'students': names_averages,
  }

Spoiler
.
.

.
.
.
.
.
.
.
Aqui mi solucion:

def get_student_average(students):
  # Tu código aquí 👈
  class_average = round(sum([sum(x['grades']) / len(x['grades']) for x in students]) / len(students), 2)
    
  for i in students:
    i['average'] = round(sum(i['grades']) / len(i['grades']), 2)
    del i['grades']
  new_dict = {'class_average': class_average, 'students': students}
  return new_dict
def get_student_average(students):
  promedio_estudiantes={}
  clase=[]
  suma=0
  count =0
  for i in students:
      suma = sum(i["grades"])+suma
      count = len(i["grades"]) + count
      clase.append({'name':i['name'],'average':round((sum(i["grades"])/len(i["grades"])),2)})

  promedio_estudiantes={"class_average":round(suma/count,2),"students":clase}
  return(promedio_estudiantes)


o
o
o
o
o
o

def get_student_average(students):
  diccionario = {}
  lista = []
  total = 0
  total_materias = 0 
  for alumno in students:
    diccionario_alumno = {}
    suma = 0
    m = len(alumno["grades"])
    for nota in alumno["grades"]:
      suma += nota
    promedio_alumno = round(suma/m,2) 
    total += suma
    total_materias += m
    diccionario_alumno["name"] = alumno["name"]
    diccionario_alumno["average"] = promedio_alumno
    lista.append(diccionario_alumno)

  promedio_clase = (round(total / total_materias, 2) )
  diccionario["class_average"] = promedio_clase
  diccionario["students"] = lista
  return diccionario


print(get_student_average([
  {
    "name": "Pedro",
    "grades": [90, 87, 88, 90],
  },
  {
    "name": "Jose",
    "grades": [99, 71, 88, 96],
  },
  {
    "name": "Maria",
    "grades": [92, 81, 80, 96],
  },
])
) 


.
.
.
.
.
.
.
.
.
.
.
.
.

def get_student_average(students):
  # Diccionario de resultados y variable para almacenar el promedio de la clase
  result = {}
  class_average = 0
  # Bucle para calcular el promedio individual y eliminar la llave de calificaciones
  for student in students:
    student['average'] = round(sum(student['grades']) / len(student['grades']), 2)
    del student['grades']
    class_average += student['average']
  class_average /= len(students)
  # Ponemos los datos necesarios en el diccionario final
  result['class_average'] = round(class_average, 2)
  result['students'] = students
  return result



.

.
.
.

.
.
.

.
.

.
.

.
.
.

.
.
.

.
.
.
.

.
.
.

.

def get_student_average(students):
  # Tu código aquí 👈
  average_function = lambda values: round(sum(values)/len(values),2)
  student_list =  [{
      'name': student['name'],
      'average' : average_function(student['grades'])
    } 
    for student in students
  ]
  class_average = average_function([student['average'] for student in student_list])
  return {
    "class_average": class_average,
    "students": student_list
  }


*
*
*
*
*
*
*
*
Dejo mi humilde código por aquí, por si se les hace interesante 😃 :

def get_student_average(students):
  sum_class_avarage = 0
  returning_dictionary = {
    "class_average": 0,
    "students": []
  }

  for student in students:
    sum_student_grades = sum(student["grades"])
    avarage_student_grades = round(sum_student_grades / len(student["grades"]), 2)
    
    sum_class_avarage += avarage_student_grades
    returning_dictionary["students"].append({
      "name": student["name"],
      "average": avarage_student_grades
    })
  
  returning_dictionary["class_average"] = round(sum_class_avarage / len(students), 2)

  return returning_dictionary 

spoiler*
*
*
*
*
*
*
*
*
*
*
*

def get_student_average(students):
  # Tu código aquí 👈":[]}
  j = 0
  class_averages={"class_average": "", "students": []}
  sum_averages = 0
  for student in students:
    student_output ={"name":"","average":0}
    j +=1
    sum = 0
    i = 0
    for grade in student["grades"]:
      sum +=grade
      i+=1
    average = round(sum/i,2)
    sum_averages += average
    student_output["name"] = student["name"] 
    student_output["average"] = average
    class_averages["students"].append(student_output)
  class_averages["class_average"]= round(sum_averages/j,2)
  print(class_averages)
  return class_averages  

.
.
.
.
.
.
.
.

def get_student_average(students):
  total_class = 0
  students_average = {'class_average': 0, 'students': []}
  for student in students:
    total_score = 0
    for score in student['grades']:
      total_score += score
    average = round((total_score/len(student['grades'])), 2)
    students_average['students'].append({'name': student['name'], 'average': average})
    total_class += average
  students_average['class_average'] = round((total_class/len(students)),2)
  return students_average
  pass


.
.
.
.
.

def get_student_average(students):
  # Tu código aquí 👈
  students_average = {'class_average' : 0, 'students' : [] }
  class_size = len(students)
  class_total = 0
  
  for student in students:
      student_average = round(sum(student['grades']) / len(student['grades']), 2)
      class_total += student_average
      students_average['students'].append({
          'name': student['name'],
          'average': student_average
      })
      
  students_average['class_average'] = round(class_total / class_size, 2)
  return students_average

def get_student_average(students):
    students_average = []
    
    for student in students:
        sum_grades = sum(student["grades"])
        num_grades = len(student["grades"])
        average = round(sum_grades / num_grades, 2)
        students_average.append({
            "name": student["name"],  
            "average": average
        })
    
    class_grades = sum(student['average'] for student in students_average)
    class_length = len(students_average)
    class_average = round(class_grades / class_length, 2)

    return {
        "class_average": class_average,
        "students": students_average
    }


*
*
*
*
*

def get_student_average(students):
    list_class_average = []
    class_average = 0
    list_students = []
    average = 0
    for student in students:
        average = round(sum(student['grades']) / len(student['grades']), 2)
        list_class_average.append(average)
        list_students.append({'name': student['name'], 'average': average})
    class_average = round(sum(list_class_average) / len(list_class_average), 2)
    class_list = {'class_average': class_average, 'students': list_students}
    return class_list
undefined