11. Count (my code works in Canopy, but not here)


#1



11. Count https://www.codecademy.com/en/courses/python-intermediate-en-rCQKw/2/1?curriculum_id=4f89dab3d788890003000096#

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

But in Canopy, it words fine with a result of 0, which is quite weird. Could anyone tell me why my code is wrong? Many thanks!!


def count(sequence, item):
    
    times=0

    for item1 in sequence:
        if item in sequence:
            times+=1
            sequence.remove(item)

    return times


#2

I don't think you need

sequence.remove(item)

as you don't need to remove anything from the list if you are counting.

Another thing is...

When you are looping, you typed:

for item1 in sequence:
    if item in sequence:

It's a little off. What about item1 (all the items in the sequence)?

You could try:

...
for item1 in sequence:
   if item1 == item:
...

#3

Yep, I see! Thank you sooo much!

At that time, maybe I thought if I didn't remove it, I would count it twice when it comes to the second item...

But, it does work in Enthought Canopy, which provides a Python environment...


#4

Different IDEs interpret the code differently from codeacademy I guess. And it also depends on the type of Python you have (eg. I have Wing IDE and Python 2 so the syntax for the print statement is different).


#5

def count(sequence, item):

times=0

for item1 in sequence:
    if item1==item:
        times+=1
print times
return times

count([1,1,1,1],0)