Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
    ]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading