I have two variables, x and y, where x is a number and y is a list of numbers.
I have to define a function count which determines how many times x appears in y, for instance,
count(1,[2,1,3,1,4])
should return 2.
Thank you in advance for your suggestions.
NB. I am not allowed to use the in-built count function, i.e. y.count(x).
You can use a generator expression and sum function like this
sum(item == x for item in y)
You can put that in a function, like this
def counter(my_list, key):
return sum(item == key for item in my_list)
assert counter([2, 1, 3, 1, 4], 1) == 2
assert counter([2, 1, 3, 1, 4], 5) == 0
assert counter([2, 1, 3, 1, 4], 2) == 1
This works because, in Python booleans are subclasses of integers. So, True will be treated as 1 and False will be treated as 0. In our case, we take each element from my_list and check if it is equal to the key. If they are equal, it evaluates to 1 otherwise 0. Then we sum the entire result.
Its already built-in to Python:
>>> from collections import Counter
>>> Counter([2,1,3,1,4])[1]
2
If you want to do it the "long" way, use a dictionary:
d = {}
for i in [2,1,3,1,4]:
d.setdefault(i, 0)
d[i] += 1
print(d[1]) # prints 2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With