Will S
Will S

Reputation: 1461

Count the number of occurrences of a given item in a (sorted) list?

I'm asked to create a method that returns the number of occurrences of a given item in a list. I know how to write code to find a specific item, but how can I code it to where it counts the number of occurrences of a random item.

For example if I have a list [4, 6 4, 3, 6, 4, 9] and I type something like

s1.count(4), it should return 3 or s1.count(6) should return 2.

I'm not allowed to use and built-in functions though.

In a recent assignment, I was asked to count the number of occurrences that sub string "ou" appeared in a given string, and I coded it

if len(astr) < 2:
    return 0
else:
    return (astr[:2] == "ou")+ count_pattern(astr[1:])

Would something like this work??

def count(self, item):
    num=0
    for i in self.s_list:
        if i in self.s_list:
            num[i] +=1
def __str__(self):
    return str(self.s_list)

Upvotes: 1

Views: 7931

Answers (4)

Eliezer
Eliezer

Reputation: 7347

Actually the most efficient method in terms of Big-O would be O(log n). @pst's method would result in O(log n + s) which could become linear if the array is made up of equal elements.

The way to achieve O(log n) would be to use 2 binary searches (which gives O(2log n), but we discard constants, so it is still O(log n)) that are modified to not have an equality test, therefore making all searches unsuccessful. However, on an unsuccessful search (low > high) we return low.

In the first search, if the middle is greater than your search term, recurse into the higher part of the array, else recurse into the lower part. In the second search, reverse the binary comparison.

The first search yields the right boundary of the equal element and the second search yields the left boundary. Simply subtract to get the amount of occurrences. Based on algorithm described in Skiena.

Upvotes: 1

Stellarator
Stellarator

Reputation: 440

This seems like a homework... anyways. Try list.count(item). That should do the job.

Third or fourth element here:

http://docs.python.org/tutorial/datastructures.html

Edit:

try something else like:

bukket = dict()
for elem in astr:
    if elem not in bukket.keys():
        bukket[elem] = 1
    else:
        bukket[elem] += 1

You can now get all the elements in the list with dict.keys() as list and the corresponding occurences with dict[key].

So you can test it:

import random

l = []

for i in range(0,200):
    l.append(random.randint(0,20))

print l
l.sort()
print l

bukket = dict()
for elem in l:
    if elem not in bukket.keys():
        bukket[elem] = 1
    else:
        bukket[elem] += 1


print bukket

Upvotes: 0

user166390
user166390

Reputation:

If this list is already sorted, the "most efficient" method -- in terms of Big-O -- would be to perform a binary search with a count-forward/count-backward if the value was found.

However, for an unsorted list as in the example, then the only way to count the occurrences is to go through each item in turn (or sort it first ;-). Here is some pseudo-code, note that it is simpler than the code presented in the original post (there is no if x in list or count[x]):

set count to 0
for each element in the list:
   if the element is what we are looking for:
      add one to count

Happy coding.

Upvotes: 3

phihag
phihag

Reputation: 287805

If I told you to count the number of fours in the following list, how would you do it?

1 4 2 4 3 8 2 1 4 2 4 9 7 4

You would start by remembering no fours yet, and add 1 for each element that equals 4. To traverse a list, you can use a for statement. Given an element of the list el, you can check whether it is four like this:

if el == 4:
  # TODO: Add 1 to the counter here

In response to your edit:

You're currently testing if i in self.s_list:, which doesn't make any sense since i is an element of the list and therefore always present in it.

When adding to a number, you simply write num += 1. Brackets are only necessary if you want to access the values of a list or dictionary.

Also, don't forget to return num at the end of the function so that somebody calling it gets the result back.

Upvotes: 2

Related Questions