Reputation: 61
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).
Upvotes: 2
Views: 975
Reputation: 174728
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
Upvotes: 3
Reputation: 239683
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.
Upvotes: 5
Reputation: 32197
Why not use a loop:
def count_occurences(num, lst):
return len([i for i in lst if i==num])
#or return sum(1 for i in lst if i==num)
>>> print count_occurences(1, [2,1,3,1,4])
2
Upvotes: 2