"count" need help fails on count([4, 'foo', 5, 'foo'],5). It returns 0 when it should return 1


#1



what is wrong with my code please help people


def count(sequence,item):
    found=0
    if sequence is list or str:    
        for a in range(len(sequence)):
            if str(a) in sequence:
                found+=1
                return found
            else:
                continue
    elif sequence is int or float:
        for a in range(len(str(sequence))):
            if str(a) in sequence:
                found+=1
                return found
            else:
                continue
    return found


#2

You are overthinking for a little. As first,you don't need the first 'if' statement.
Secondary, the if sequence[i] == item statement is enough to check the sequensity so the loop looks like this:

for i in range(len(sequence)):
   if sequence[i] == item:
        found += 1

The else statement could just return nothing (or found += 0 if you want)

    else:
        found += 0
return found

You don't need the elif statement!!!


#3

thank you it worked well and i understood :+1:


#4

You're welcome, hope you understood well. I'm sorry for a stupid guestion but can you press the 'solution' button at the post that solves the problem. Thank you. :slight_smile:

I am new at the forums so I need them.

Really.


#5

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