Python function to count divisible numbers in a list?
Question:
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:
Could someone advice me on what approach to take, please?
I tried a for loop that finds the divisible numbers and adds them to a counter, but that is not working.
Answers:
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
The error message clearly indicated the problem. So you could fix it and make it working like this:
def count_divisible(L, n):
count = 0
for x in L:
if x % n == 0:
count += 1
return count # just return the counts
# version 2 - Generator Expression
def count_divisible2(L, n):
return sum(1 for x in L if not x % n)
if __name__ == '__main__':
assert count_divisible([2,3,4,5], 2) == 2
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:
Could someone advice me on what approach to take, please?
I tried a for loop that finds the divisible numbers and adds them to a counter, but that is not working.
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
The error message clearly indicated the problem. So you could fix it and make it working like this:
def count_divisible(L, n):
count = 0
for x in L:
if x % n == 0:
count += 1
return count # just return the counts
# version 2 - Generator Expression
def count_divisible2(L, n):
return sum(1 for x in L if not x % n)
if __name__ == '__main__':
assert count_divisible([2,3,4,5], 2) == 2