11. count


#1

<PLEASE USE THE FOLLOWING TEMPLATE TO HELP YOU CREATE A GREAT POST!>

<Below this line, add a link to the EXACT exercise that you are stuck at.>

<In what way does your code behave incorrectly? Include ALL error messages.>

I worried about list input such as [ [1,[1,2],[1,2,3]],1]

above code can’t count 1 in [1,2], and [1,2,3]

so for count 1, should I check element type until it does not find ‘list’ type?

<What do you expect to happen instead?>

```python
def count(sequence,item):
    seq_len=len(sequence)
    count = 0
    for i in range(seq_len):
        if type(sequence[i])!=list:
            if sequence[i]==item:
                count += 1
    
    else: #list type
        element_len=len(sequence[i])
        
        for j in range(element_len):
            if sequence[i][j]==item:    
                count +=1
return count
<do not remove the three backticks above>

#2

Your code looks pretty solid! The reason it’s not working is because your indentation isn’t the best, and so your code is executing in the wrong way. Also, you need to convert element_len to a string before you can measure its length. If you want the code that works, here you go:

def count(sequence, item):
    seq_len = len(sequence)
    count = 0
    for i in range(seq_len):
        if type(sequence[i]) != list:
            if sequence[i] == item:
                count += 1

        else:  # list type
            element_len = len(str(sequence[i]))

            for j in range(0,element_len):
                if sequence[i][j] == item:
                    count += 1


    return count

#3

Thank you for replying my question :grinning:

indentation error is mistake during copy codes from my python script. :sob:

but your code is not working.

in following case,

input_list=[[1,[1,2],3],[1,2]]
print count(input_list,1)

error occurs because string length of “”[1, [1, 2], 3]" is 14.

so I think code should be modified like this.

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

    if type(sequence[i])!=list:
        if sequence[i]==item:
            count += 1
    
   
    else: #list type
        element_len=len(str(sequence[i]))
        stored_string=str(sequence[i])
        #print stored_string
            
        for j in range(0,element_len):
            if stored_string[j]==str(item):    
                count +=1

return count

#4

my mistake. I probably should’ve rewritten it all to be more efficient, you’re making the code way too complicated than it needs to be. Take a look at my rewritten code:

def count(sequence, item):
    counted = 0
    for thing in sequence:
        if thing == item:
            counted += 1
        else:
            pass
    else:
        return counted

#5

Retrospective

When we reach the unit on Advanced Topics we get exposed to two really powerful features in Python which we can come back to this problem and try out…

filter()
lambda

filter is an iterator that builds a list of all items that meet the conditional in the function.

lambda is the function.

filter(function, iterable)

is the general syntax of this function. We give it a selection function, and a list or other iterable.

The argument function is anonymous, so only needs to be an expression, not a definition. That’s where lambda jumps in to fulfill the roll.

lambda variable: conditional_on_variable, iterable

We can test the following, but it is not a valid submission, even if it works. It jumps ahead of the curve, so this would be a retrospective of the exercise once the Advanced module is completed.

>>> def count(haystack, needle):
    return len(list(filter(lambda x: x == needle, haystack)))

>>> count([2,3,4,5,4,5,6,7,6,5,4,5,6,7,6,5,4,3,4,3,2,1,2,3,4,5], 2)
3
>>> count([2,3,4,5,4,5,6,7,6,5,4,5,6,7,6,5,4,3,4,3,2,1,2,3,4,5], 6)
4
>>> 

#6

Continuing the above, let’s see if we can make it work with an unflattened list…

First, we create a function that flattens a list of reasonable depth:

def flatten(n):
    for i in n:
        if type(i) is list:
            n += test.pop(test.index(i))
    return n

Next we update the above count function:

>>> def count(haystack, needle):
    return len(list(filter(lambda x: x == needle, flatten(haystack))))

>>> test = [1,2,3,[2,3,4,5],6,[1,2,3,7,8],9,[2,3,10,[1,2,3,11,12,[2,3,13,14],15],16,17],18]
>>> count(test, 2)
6
>>> 

After some tinkering, we have this…

def flatten(a_list):
    for i, x in enumerate(a_list):
        if type(x) is list:
            a_list += a_list.pop(i)
    return a_list

def get_count(haystack, needle):
    return len(list(filter(lambda x: x == needle, flatten(haystack))))

def count(m, n):
    print ("{} count => {} \nlist => {!r}".format(n, get_count(m, n), sorted(m)))

test = [1,2,3,[2,3,4,5],6,[1,2,3,7,8],9,[2,3,10,[1,2,3,11,12,[2,3,13,14],15],16,17],18]
  
count(test[:], 1)
count(test[:], 2)
count(test[:], 3)
1 count => 3 
list => [1, 1, 1, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18]
2 count => 6 
list => [1, 1, 1, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18]
3 count => 6 
list => [1, 1, 1, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18]

https://repl.it/LYqK


#7

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