Count


#1



Why does this code returns 0?

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


#2

def count(sequence,item):
    #sequence = list() #comment it out
    #item = list() #comment it out
    total = 0
    for i in sequence:
        if i in item: # 'in' keyword.
            total += 1
    return total

There are many errors in your code.I have marked the errors by commenting them out.

try this.

#program to find frequency of an item in a list/string
def count_item(seq,item):
    counter = 0
    for x in seq:
        if x == item:
            counter += 1
    return counter
print(count_item([1,2,3,4,2],2))

#program to find common items between two lists/strings
def count_item(seq,item):
    counter = 0
    for x in seq:
        if x in item:
            counter += 1
    return counter
print(count_item([1,2,3,4,2],[2,3,4,6,7])

I hope you get the idea.


#3

It prints out right answer but error is the same
Oops, try again. Your function fails on count([4, 'foo', 5, 'foo'],5). It returns 0 when it should return 1.


#4

Link me or mention exact question you're having problem .


#5

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

The functions works good and it gives the correct answer but it gives an error :
Oops, try again. Your function fails on count([4, 'foo', 5, 'foo'],5). It returns 0 when it should return 1.


#6

def count(sequence,item):
    counter = 0
    for x in sequence:
        if x == item: #you made a mistake here and other two points that i pointed out in first answer.
            counter += 1
    return counter

It works fine for me!

Even I tested it using IDLE and it works fine!


#7

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