11. Count - is it possible to make less coding?


#1

I solved the Lesson, but I think the answer could be done with less effort. Any suggestions on how to make a less code lines?

def count(sequence, item):
    if type(sequence) == str:
        counter = 0
        for y in sequence:
            if y == item:
                counter +=1
        return counter
        
    elif type(sequence) == list:
        counter = 0
        for y in sequence:
            if y == item:
                counter +=1
        return counter
    else:
        c = 0
        for x in str(sequence):
            if x == str(item):
                c+= int(x)
        return c


#2

well, your code for strings and lists is exactly the same? The requirement of the exercise are more then is actually validated, this:

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

is enough to pass the exercise


#3

def count(sequence, item):
    return sequence.count(item)

This is also enough to pass the exercise


#4

yea, of course you can solve the problem with built in functions, but it is not as much fun


#5

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