11. Count


#1



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

The code corrector says my code counts incorrectly:

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


However, when I use the given entry, count([4, 'foo', 'foo'],5), my code does count appropriately, printing,

[4, 'foo', 'foo']

[4, 'foo', 'foo']
0
None

I would like to know if there is, indeed, anything wrong with my code. Thanks!


def count(sequence,item):
    
    print sequence
    num = 0
    size = len(sequence)
    for i in range(size):
        if item in sequence:
            sequence.remove(item)
            num += 1
            print sequence
    print
    print sequence
    print num
    return num
    
count([4, 'foo', 'foo'],5)


#2

using remove causes problems with the validation. Please try not to use remove, if you do want to use remove, do so on a copy of the list, you might get lucky


#3

I altered my code so as to make changes to a copy of the list. My code now is as follows

def count(sequence,item):

copy = sequence

print sequence
num = 0
size = len(sequence)
for i in range(size):
    if item in copy:
        copy.remove(item)
        num += 1
        print copy
print
print copy
print num
return num

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

However, I still have the same problem: my printed results are fine, and the corrector says otherwise D:


#4

that is not a copy, that is a reference to the same list, make a copy:

copy = list(sequence)

#5

Bingo! That's something I've been really missing, I guess. I can't thank you enough!


#6

your solution still could use some improvement, see if you can improve it


#7

Hello!

Why not since:

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


#8

why not since what?


#9

I wanted to say that we can do so. It looks easier.
Is it better?


#10

your solution is a better then cloudpro69289 solution, yes


#11

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