Problem in Count


#1

This is my code for total number of matching items in the given sequence ,but i am getting this error "Oops, try again. Your function fails on count([6, 2, 3, 4, 5, 6],6). It returns 1 when it should return 2."

Please guide me whats my mistake?????

def count(sequence, item):
    found = 0
    for num in sequence:
        if num == item:
            found += 1
            return found
        if item not in sequence:
            return 0

#2

take a good moment to consider the indent of your program and the routes your program takes because of it

Also, realize that a function ends the moment a return keyword is reached


#3

Hi, am I the only one troubling around item that is not necessarily 1 slot long?

This worked for me and approved as the result, but it should find also non-1 slot long items.

def count(sequence, item):
    found=0
    for c in range(0,len(sequence)):
        if item==sequence[c]:
            found+=1
    return found

#4

you mean you also want your function to work for:

count([6, 2, 3, 4, 5, 6],[5, 6])

?


#5

Hi Stetim94 yes, that would be nice to practice.


#6

i can help you with that, but i am not fully going to code it for you. What do you think you need? Also, lets say we have this:

count([6, 2, 3, 4, 5, 6],[5, 6])

what should be the output? two options:

[2, 3, 4]

or:

[6, 2, 3, 4]

the six doesn't gets removed because it is not [5, 6]


#7

Hi,

I was thinking about an universal count function. For strings I have managed to create this, which can count number occurences of substring of any length in a string. Wanted to ask if there is a chance to make this universal:

def count(sequence, item):
    sequence=str(sequence)
    item=str(item)
    found=beg=0
    hit=""
    item_len=len(item)
    while beg+item_len <= len(sequence):
        for c in range(beg,item_len+beg):
            hit=hit+sequence[c]
        if hit==item:
                found+=1
        hit=""
        beg+=1
    return found

Thanks.


#8

wait this is count, i got confused with remove_duplicates for a second.

I still don't have a clear picture of what you want, and unless you can provide this for me, i can't help you

Give me a couple of cases (strings, lists, integers) and there desired output. You first have to think what you want


#9

A post was split to a new topic: Count


#10

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