frequency count or number of occurences of a number in an array
John Machin
sjmachin at lexicon.net
Wed Mar 12 07:58:24 EDT 2008
On Mar 12, 10:29 pm, Bernard <bernard.ch... at gmail.com> wrote:
> Hey Larry,
>
> that one is fairly easy:
>
> >>> from array import array
> >>> array('i', [1, 2, 3, 4, 5, 1, 2])
> >>> def count(x, arr):
>
> cpt = 0 # declare a counter variable
> for el in arr: # for each element in the array
> if el == x: # when it is equal to the 'x' value
> cpt+=1 # increment the counter variable by one
> return cpt # return the counter after the loop>>> count(1,a)
>
> 2
>
Hey Bernard, you have just laboriously reinvented the count method:
>>> from array import array
>>> a = array('i', [1, 2, 3, 4, 5, 1, 2])
>>> a.count(1)
2
>>>
which Larry has already said doesn't do the job -- the job is to
create a histogram!!
More information about the Python-list
mailing list