So far, I think I'm doing it right however it doesn't seem to generate the results I wanted.

def occurrence(e,List):
    for item in List:
        s = 0
        if item == e:
            s += 1
    return s

Basically I want my function to count how many times e occurs in List. So basically I can do something like:

">>> occurrence(1,[1,2,3,4,5,1,1])
"3
">>>

However it seems like its not looping, and I'm assuming the loop stops after the first time "item" is "e".

So when I run the function I get

">>> occurrence(1,[1,2,3,4,5,1,1])
"1
">>>

The biggest thing here I simplicity, I'm looking to get desired results simply with if, while, for, etc loops.

Don't use "List" as your variable name, this is a reserved python keyword. Try replacing it with something like "mylist".

Also, python's list have building count features so you can do something like:

for x in mylist:
print x, mylist.count(x)

Good point regarding List as the variable name. However, I want to refrain from using built in functions. I have a working one with the built in count functions, but it defeats the purpose of the excercise. Essentially I'm trying to brute force the answer using loops. Although I'm not sure what's incorrect about the function

I've tried return s += 1 as well to + 1 to the previous s for each time the e and mylist were equal. But I'm questioning whether my if statement is wrong?

Simple debugging will point out the error. Try running the code with these additional print statements.

def occurrence(e, input_list):
    for item in input_list:
        print "checking" item, e  ## test for checking every item
        s = 0
        if item == e:
            print "     found, s =", s  ## this will clarify the problem
            s += 1
    return s

Builtins are the way to do it, but in your function you reset s to zero each loop because it is inside the loop. It needs to be set to zero before the loop.

Cool, I appricate the help! I see the function just sets s to 0 each time a pair is found.

Now I'm bit confused, do you have an example in which the loop adds itself. I always though s = s + 1 would just add itself.
If I can explain it clearly, my logic is:

s = 0
- function starts with s at 0 meaning 0 pairs are found

If 1 pair is found then it would be:
s = 0 + 1 = 1

So when a 2nd pair is found
s = 1 + 1 = 2

and so fourth

At least that's what I assume the function should work through this method.

And it work! Looked up how to do a counter loop, and loops were just placed incorrectly to obtain the results I desired. Thanks for the help!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.