views:

168

answers:

5
def fun1(a,x):
    z = 0
    for i in range(len(a)):
        if a[i] == x:
            z = z + 1
    return z
+8  A: 

It counts and returns the number of occurrences of x in the array a. More broadly, a can be any indexable object. See 5.3.2 Subscriptions of the Python Language Reference v2.6.3:

5.3.2. Subscriptions

A subscription selects an item of a sequence (string, tuple or list) or mapping (dictionary) object:

 subscription ::=  primary "[" expression_list "]"

The primary must evaluate to an object of a sequence or mapping type.

If the primary is a mapping, the expression list must evaluate to an object whose value is one of the keys of the mapping, and the subscription selects the value in the mapping that corresponds to that key. (The expression list is a tuple except if it has exactly one item.)

If the primary is a sequence, the expression (list) must evaluate to a plain integer. If this value is negative, the length of the sequence is added to it (so that, e.g., x[-1] selects the last item of x.) The resulting value must be a nonnegative integer less than the number of items in the sequence, and the subscription selects the item whose index is that value (counting from zero).

A string’s items are characters. A character is not a separate data type but a string of exactly one character.

cletus
+1, that's exactly right.
JL
Not necessarily an array, it can be any indexable object
Vinko Vrsalovic
Of course `for i in a:` is better because it is more efficient and will also work with any iterable
gnibbler
And if you need an index for some purpose you can always just do `for i, j in enumerate(a):`
Chris Lutz
+3  A: 

Counts the number of x repeated elements in the array a.

bruno conde
+4  A: 

It counts the amount of elements in a which are equal to x. It assumes a is indexable (like a string or a list)

def fun1(a,x):              #Defines a function with 2 parameters, a and x
    z = 0                   #Initializes the counter
    for i in range(len(a)): #len(a) returns the length of a, range(len(a)) 
                            #returns an enumerator from 0 to len(a) - 1
        if a[i] == x:       #which is then used here to index a
            z = z + 1       #if the ith element of a is equal to x, increment counter
    return z                #return the counter

Given the title change, you can execute the function like:

> fun1("hola mundo","o")
2

or

> fun1([1,2,3,4,4,3,2,1],4)
2
Vinko Vrsalovic
+1  A: 

Shorter version of the code above:

>>> def f(a, x):
...     return sum(1 for e in a if e == x)
... 
>>> f([1, 2, 3, 4, 3, 7], 3)
2

This uses a generator expression to construct an iterable which yields 1 for each occurrence of x in a. sum adds them. Even slightly shorter is to use len and filter (this code needs a conversion to list if using Python 3.x):

>>> def f(a, x):
...     return len(filter(x.__eq__, a))
... 
>>> f([1, 2, 3, 4, 3, 7], 3)
2

The above functions work for any iterable object. As SilentGhost and gnibbler point out, for string objects and mutable sequence types there is the count method, which allows for an even more concise notation:

>>> [1, 2, 3, 4, 3, 7].count(3)
2
Stephan202
what about `.count`?
SilentGhost
.count is best when you have that method available
gnibbler
you should use `operator.eq` instead of `x.__eq__` it will be more efficient
gnibbler
@SilentGhost: valid point. The advantage of the above is that it works for any iterable. I will update the answer.
Stephan202
@gnibbler: could you explain why that is so?
Stephan202
You'll leave the poor newbie totally confused :-)
Vinko Vrsalovic
+3  A: 

Code to execute the function?

fun1("hello world","l")
gnibbler
This is the first answer to the real question :)
Ber