11. count - Need help please, I can't figure out what's wrong with the code


#1

Here's the code I have so far:

def count(sequence,item):
    c = 0
    while item in sequence:
        sequence[sequence.index(item)]="*"
        c += 1
    return c

print count([1,2,1,1],1)
print count([4, 'foo', '*', 'foo'],5)

It works for me, see this screen shot:

But I don't understand the error message I get when I try to submit the lesson (because count([4, 'foo', '*', 'foo'],5) does, indeed, return a 0:

Oops, try again. Your function fails on count([4, 'foo', '', 'foo'],5). It returns 1 when it should return 0.*


#2

Hint: You are not supposed to modify the list. Notice what you are doing on line 4.

Additionally, your code will go into an infinite loop on such an input: print count(["*"], "*") So, it is not the best method :wink: There is a much simpler method, remember not to overthink your solution.


#3

Thanks for your help! You were right, there was a better solution, which I eventually found.


#4

Please share , been struggling with this for a little while now

def count(sequence,item):
    total = 0
    for x in sequence:
        if x == item:
            total += 1
    return total

print count([1,2,1,1],1)
print count([4, 'foo', '*', 'foo'],5)

This is all I can offer for interpretation.


#5

Seems to be working, what error are you getting?


#6

It just worked which if very peculiar.
I could have sworn it kept of giving me an error, can't remember it though.
Thanks