Search code examples
pythonnested-loops

nested loop does not return any value - low level


alumnos = ["Pepe", "Juan", "Margarita", "Ariana"]

notas = [99, 99, 99, 80]

def pregunta_3(alumnos, notas):
    result = []

    i = 0
    while i < len(alumnos):
        alumno = alumnos[i]
        contador = notas.count(alumno)
        if contador > 2:
            result.append(alumno)
        i += 1
    return result

resultado = pregunta_3(alumnos, notas)

print("Resultado de la pregunta 3:", resultado)

I don't know why, but my code returns empty brackets, it should return the names of the people when there are at least 3 people with the same value.I'm just learning how nested loops work, how should I change the code? it's supposed to return ["Pepe", "Juan", "Margarita"]


Solution

  • It looks like you meant to write:

    contador = notas.count(notas[i])
    

    That fixes the problem. To make the code nicer, you can use for instead of while, and zip instead of an index like i:

    def pregunta_3(alumnos, notas):
        result = []
        for n, alumno in zip(notas, alumnos):
            if notas.count(n) > 2:
                result.append(alumno)
        return result
    

    Then you can use a list comprehension:

    def pregunta_3(alumnos, notas):
        return [
            alumno
            for n, alumno in zip(notas, alumnos)
            if notas.count(n) > 2
        ]
    

    However each call to .count scans through the whole list, so this is an O(n^2) algorithm that will be problematically slow for >1000 elements. Here's a more efficient O(n) approach:

    from collections import Counter
    
    def pregunta_3(alumnos, notas):
        notas_counts = Counter(notas)
        return [
            alumno
            for n, alumno in zip(notas, alumnos)
            if notas_counts[n] > 2
        ]