Count (how to count another list)


#1



This code works for integer, string, but doesn't work for another lists (nested lists).

Does anybody know how to rewrite the code for nested lists?

def count(sequence, item):
    result = 0   
    for i in sequence:
        if i == item:
            result += 1  
    print result
    return result
count(['This', 4, 'aaa', 'hg', 4, 'aaa'], 'aaa')


Replace this line with your code.


#2

seems to work fine?

def count(sequence, item):
    result = 0   
    for i in sequence:
        if i == item:
            result += 1  
    print result
    return result
count([[1,2,3],'a','c'], [1,2,3])

for what case wouldn't it work?


#3

for this one doesn't work:

count([[1, 'aaa'], 1, 'ooo', [2, 'ooo', 1], ['aaa', 1]], 1)


#4

the output is 1 but I thought it should be 4


#5

this depends, should this one:

count([[1,2,3],'a','c'], [1,2,3])

also valid? in other words, is it allowed for item to be a list? because that makes a huge difference


#6

here is an example:

def count(sequence, item):
    result = 0   
    for i in sequence:
        if type(i) == list:
            for j in i:
                if j == item:
                    result += 1  
        else:
            if i == item:
                result += 1
    print result
    return result
count([[1, 'aaa'], 1, 'ooo', [2, 'ooo', 1], ['aaa', 1]], 1)

of how to achieve this, you need to loop over the inner list


#7

Thanks for your answer. It's really helped me. Now it's clear.


#8

It would be a completely different search pattern to also loop through any sub-lists.
What you would do is that if the value is a list, you would then call count (count would call itself) to determine if the value to be found is in that sub-list.
You'd probably also want to compare the sub-list itself to the value to be found, in case that value is a list.


#9

it works fine for me!!!

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


#10

if you would have read the question, fox-cub wanted to change count, lets say you have this:

count([[1, 'aaa'], 1, 'ooo', [2, 'ooo', 1], ['aaa', 1]], 1)

your function would return 1, fox-cub wants his function to return 4 (also finding the 1's inside the nested lists)

not sure what you are trying to say with your answer


#11

for that one it doesnt work..
i thought for the one that is I did...


#12

Not solution but a hint In two dimensional arrays you need two for loops to access an item.


#13

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