Codeacademy says this code fails?


#1



Practice makes perfect


With the code below I get the error message

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


However as I can tell from the included 'print' command it is in fact returning 0 . 0 is printed to the console screen.


def count(sequence,item):
    counter = 0
    while item in sequence:
        
        sequence.remove(item)
        counter = counter + 1
       
    return counter
    

print count([4,'foo','foo'],5)


#2

Hi @textjumper63560,

Codecademy's message is incorrect. However, your code alters the original list that is passed to the function, which is generally not a good idea, unless one of the purposes of the function is to make changes to the list.

Use a for loop instead of a while loop. The loop header might look something like this ...

    for word in sequence:

Then, inside the loop, you can compare word to item, and increment counter when appropriate.

EDITED (April 21, 2017) to add link to exercise: Python: Practice Makes Perfect: 11. count


#3

Thanks, I fixed it, although codeacademy is still marking that one incorrectly. (Last thing left in the the course!)

cheers, G


#4

Thanks, @textjumper63560, for pointing out the problem.

As you have discovered, Codecademy's submission correctness test (SCT) for this exercise is quite buggy. For example, it passes this code, even though it is incorrect ...

def count(sequence, item):
    while len(sequence) > 0:
        del sequence[0]
    return 0

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

Here's the output ...

0

The above code does not even attempt to count the number of occurrences of item in sequence, however, it is just fine as far as the SCT is concerned.


#5

Hello @textjumper63560,

If Codecademy is still not passing your submission, you can make a small change to the code from your original post to get it to pass and to produce the correct result.

You have a variety of options for correcting the code. The simplest change you can make is to have it work with a new list so that it leaves the original one unchanged. Simply insert the following line right after the function header, and leave everything else as it was in the original post ...

    sequence = list(sequence)

The expression, list(sequence), creates a new list that is a copy of sequence. The statement assigns that new list to sequence. Thereafter, the function modifies the new list, leaving the original one intact. It produces the correct result and Codecdemy passes it.

Let us know how it works out, and thanks again for noticing the SCT bug.


#6

Thanks. That worked, with the following code:

def count(sequence,item):
    counter = 0
    mylist = list(sequence)
    for word in mylist:
        
        if word == item:
            counter = counter + 1
       
    return counter
    

print count([4,'foo','foo'],5)

#7