Count 11/15


Hey this is my code..
, , ,
def count(sequence,item):
found = 0
for i in range(len(sequence)):
if sequence[i] == item:
found += 1
return found

print count (["This is working, is it??"] , "it")
, , ,

This doesn't return anything for string, anyone can help??


Hi @ankurlvv ,

Because the code that you posted is not formatted, it is difficult for other users to read and debug it. After code has been pasted into the editing window for posting, you can format it by selecting it, and then by clicking the </> button above the editing area. Alternatively, you can place three backquotes on the line before the code and three backquotes on the line after the code. This will enable us to see important details, such as the indentation and underscores. If you use the backquotes, your code will be color-coded, making it especially easy to read.

Your final line of code calls count to look for individual items that match "it" in this list ...

["This is working, is it??"]

However, "it" only exists as a substring of the single string in that list, so 0 is returned.

If you do this, 1 will be returned ...

print count (["This", "is", "working", ",", "is", "it", "??"] , "it")


@appylpye thanks i w'll edit next tyme when i w'll something. I got it, what you are trying to say , thanks!!

but What if we print string there like in code, for that how i m gonna find out for substring??


This one is simpler than it looks. There is no need to refer to the type of variables being used.

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


Hi @ankurlvv ,

For counting non-overlapping substrings within a string, there is already a string method named count. Here is an example of how to use it ...

seq = "It is it, isn't it?"
look_for = "it"
print seq.count(look_for)

Output ...



Thanks buddy, but the solution you are giving isn't gonna give result for string with sub-strings, see @appylpye answer that's what i was looking for


@appylpye thanks buddy, i got it.!!! but is there any way without using count to answer that?
just curious.. :smile:


EDIT (January 15, 2016):

The following is offered in answer to @ankurlvv's question about how we can write a function that counts the occurrences of substrings within a string, and is not intended as an example of code that should be submitted as a solution to Exercise 11: count.

Hi @ankurlvv ,

Here is a function that counts substrings, including ones that overlap:

def count_substring(whole_string, sub_string):
    res = 0
    whole_string_len = len(whole_string)
    sub_string_len = len(sub_string)
    if sub_string_len == 0:
        return 0
    for i in range(whole_string_len - sub_string_len + 1):
        if whole_string[i: i + sub_string_len] == sub_string:
            res += 1
    return res

print count_substring("banana", "")
print count_substring("banana", "na")
print count_substring("banana", "an")
print count_substring("nananana", "nan")




@appylpye hey there..

Thanks for the code, but could you please give me the detail about following line of code.

for i in range(whole_string_len - sub_string_len + 1):
if whole_string[i: i + sub_string_len] == sub_string:
res += 1
return res


Hi @ankurlvv ,

Following is the loop with comments added for explanation:

    # Start i at index 0 and loop until i is at the last index where the substring has room to start
    for i in range(whole_string_len - sub_string_len + 1):
        # Look for the substring, beginning at index i
        if whole_string[i: i + sub_string_len] == sub_string:
            # If the slice of the string beginning at index i matches the substring, increment the count
            res += 1
    # Return the final count
    return res


@appylpye Thanks buddy now i got it..


Instead of a comma it has a - operator in between the length of whole_string_len and sub_string_len which has the length of them so using "banana" and "na" it will be: range(6 - 2 + 1) ? and that raises another question about +1 since I thought it was default for step in the range function, but it's different results if I don't use +1? (Just using range(whole_string_len - sub_string_len) gives different results is what I mean?)

if "banana"[i : i + 2] is equal to "na" :
then increment plus 1

Please help, I read the comment explanations and it still is confusing to me. You probably, hopefully can see why? I understand the rest of your code, I think.


Hi, @wilest ,

When the range function is given one argument, as it is here ...

range(whole_string_len - sub_string_len + 1)

... the resulting sequence starts at 0, and ends at 1 less than the value of the argument. The ending value specified for a range is exclusive.

Let's consider this function call as an example ...

print count_substring("reverberate", "er")

Here, the whole string is "reverberate", and we are counting occurrences of the substring, "er". The length of "reverberate" is 11, and the length of "er" is 2. As we look at slices of the whole string for the substring, the last slice we look at needs to be the one that starts at the second-to-last character of the whole string. That is because it is the last place in the whole string where a slice can begin, and still have enough room to contain the substring, considering that our substring for this example is 2 characters in length.

For our example, that second-to-last character has an index of 9. Doing the math with the lengths of the whole string and the substring, we have 11 - 2, which is 9. So the index, 9, is where we want the final slice to begin. Consequently, 9 needs to be the value for i during the final iteration of the for loop. As we remember, in a range, the ending value is exclusive, therefore, we need to use 10 as the ending value. That is why we have whole_string_len - sub_string_len + 1 as the argument to range. It evaluates to 10 in this example.

Here, we are looking at the slice of whole_string that begins at index, i, and runs for the number of characters in the substring ...

if whole_string[i: i + sub_string_len] == sub_string:

Each time that the slice is equivalent to the substring, we increment res, which is the count.


Thank you very much! I had to look up slice and how it works again(practically the same way as range with none and 0 for defaults). That told me what I didn't know along with your help I got it, I think so. Thank you!!


@appylpye, your code does not work. I copied it exactly and Codecademy gave me this error:
Oops, try again. Your function fails on count([4, 'foo', 5, 'foo'],5). It returns 0 when it should return 1.
I'm not sure what to do for this exercise. I tried to make my own code first, but it didn't work either.


Hi @jrpsychgal ,

My code was provided for @ankurlvv , who needed it to solve a different problem from the one posed in this exercise. Accordingly, you should not copy and submit that code as your solution, because it will not be accepted by the submission correctness test (SCT).


Looks close to mine:

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


the SEQUENCE is a LIST[] which mean to iterate over it you covert to a LIST e.g list(sequence).
def count(sequence, item):
for num in list(sequence):
if num == item:
found += 1
return found
which will count each item in the list sequence. but not substring of the sequence.