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

Python function to count divisible numbers in a list?

I need to write a python function that takes a list as the input and calculates the number of numbers divisible by some other number, n. This is the code I have so far:

enter image description here

Could someone advice me on what approach to take, please?

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

I tried a for loop that finds the divisible numbers and adds them to a counter, but that is not working.

>Solution :

You’re returning the length of an integer, count, when you probably want to return the count itself:

def count_divisible(lst, n):
    count = 0
    for i in lst:
        if i % n == 0:
            count += 1
    return count

You can shorten your function and make it safer by checking each item is actually an int or a float:

def count_divisible_short_and_safe(lst: list, n: int) -> int:
    return len([x for x in lst if isinstance(x, (int, float)) and x % n == 0])

assert count_divisible_short_and_safe([2,3,4,5, "foo"], 2) == 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