Count error


#1



count

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


But when I run my code it is correctly returning 0 ...
0
None

why am I getting this error ?

def count(sequence,item):
    found = 0
    not_found=True
    while not_found:
        if item in sequence:
            found += 1
            sequence.remove(item)
        else:
            not_found=False
    return found
    
print count([4, 'foo', 'foo'],5)


#2

That function looks correct, so my guess is that perhaps this isn't the exact and full code that you submitted. (If you posted a link to the exercise it'd be easy for others to try to reproduce what you describe)

Also note that item in sequence and sequence.remove(item) each walk through the whole list - so if you have a list of 100 of those items then you'd walk through it 100 times and each time you walk through it it's 100 steps - 100 * 100 = 10000 .. 10000 steps isn't reasonable for counting to 100. A more reasonable way to count something is to look at each value only once.


#3

Sorry but that is the exact code. I have cut and paste it into the post, and like I say when it runs I get the right result.


#4

That still leaves me without a way of reproducing it (link to exercise)


#5

Practice makes perfect

count


#6

A post was split to a new topic: Count


#7

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.