samedi 4 septembre 2021

Counting the number of objects in a list that are divisible by another number

I'm a bit of a newbie here and having a tough time trying to figure this out!

Essentially, I'm looking to have this function count the numbers in a list that are divisible by 2.

def listDivide(numbers, divide = 2):

        result = 0

        for i in numbers:
            if i % divide == 0:
                result += 1
        print(result)

listDivide([1 ,3 ,6 ,2 ,4])

results in:

    3
    2

It appears that the list is being processed through the loop once, correctly counting the objects divisible by 2 (with no remainder using modulo), and then going back through the loop, counting the number of objects in the list based on index, and then dividing them by 2. Ex, 1, 2, 3, 4, 5

I've got to be missing something super simple here, but I cant seem to figure it out. Any help would be appreciated and thanks in advance everyone!

Aucun commentaire:

Enregistrer un commentaire