Hi, I am taking the liberty to get involved, hope that is okay.
My issue with the count-exercise is that it works fine if there is only a single string to be counted.
It fails to check if a list exists in a list though.

def count(sequence, item):
    count = 0
    for i in range(0,len(sequence)):

        if sequence[i]==item:
    return count

count([1,2,3],1) => This works and returns 1
count([1,2,3],[1,2]) => This fails: It returns 0 but is supposed to return 1

An idea I had was to concatenate all list items from "sequence" into a single string; same for the list items in "item", then apply the count-function. This would only work though if both variables contained a list so I would have to check via the type-function first of all.
My train of thoughts sounds messy and overly complicated though, could need some help here, thanks!

Problem in Count

Your logic is incorrect in the sense that your function takes two arguments (sequence) which is the list of integers and (item) which is one of the integers. So you cannot put two integers in the second argument because your function is not designed to separately give the frequency of to list items.


i am sure there is a more elegant matter, but this is roughly what i would do:

if type(item) == list:

check if item is a list. If so, check if sequence[i] equals item[0], if this is true loop over item to check if all values are present and in sequence

add a else in case item is not a list, and add there your existing code


What this should return ...


... depends upon how the problem is defined.

The instructions include this ...

The item you input may be an integer, string, float, or even another list!

However, that statement is not very specific about what the function should do if the second argument in the function call is a list.

For the solutions that most users submit, this would display 1 ...

print count([3, 7, 2, 4, [1, 2], 8, 6], [1, 2])

That is because item is the list, [1, 2], and sequence is [3, 7, 2, 4, [1, 2], 8, 6], which contains one occurrence of the list, [1, 2].

@codeheadray , it appears that if item is a list, you would like count to look for slices in sequence that correspond to item. That can be done. While Codecademy does not test for this, code that implements this provision can pass the submission correctness test (SCT).

You can use @stetim94's suggestion to test whether item is a list.

Keep in mind that we need to avoid ambiguity in defining the problem. What should the count function do if item is a list that contains a list or if sequence contains nested lists?


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