60.8k views
5 votes
PYTHON

How can I make a algorithm in python that finds how many numbers are in a row in a list?

For example:

Input:
List = [0,1,1,1,0]
num = 1

Output:
3

User Mc Kevin
by
5.3k points

1 Answer

3 votes

Answer:

This is one of the efficient ways to find the number of occurrences of a given number in a list:

def find_num(arr,n):

return len([count for count in arr if count == n])

print(find_num([0,1,1,1,0],1))

If you want a simpler version, you can try this:

def find_num(arr,n):

count = 0

for i in range(len(arr)):

if arr[i]==n:

count += 1

return count

print(find_num([0,1,1,1,0],1))

This is the simplest method:

arr = [0,1,1,1,0]

print(arr.count(1))

I think I gave you enough examples. This should get you started off easily.

If you need an explanation, I am happy to help you. BTW I started python 6 months back so even I am pretty new to this.

User Good
by
4.9k points