11. Count Lists


#1



Exercise


Hi,

Sorry if this shouldn't be a new thread, but rather an addition to an old one. I see a lot of Count threads, but I didn't see any relating to the instruction to make lists countable. My code runs fine. and I pass the level, but I tried inserting the balls list and the code ignores these numbers in counting. Any idea how to make the code look at the contents of the list?

Thanks for the help.


def count(sequence, item):
    counter = 0
    for x in sequence:
        if item == x:
            counter += 1
    print counter
    return counter
balls = [3,4,3]
count([1,2,3, balls,3,2,3], 3)


#2

A list in a list requires a second layer of iteration to access its contents. As a reference object, it has no value, outright so cannot be compared to a value (item in the above).

for x in sequence:
    if isinstance(x,list):

Now figuring out how to go forward from here is something we both need to work on, so I'll leave this with you.

Update:

Here is an elementary stab at the solution:

def count(seq, item):

    # copy original list
    sequence = seq.copy()
    print ("%r" % sequence)                  # [1, 2, 3, [3, 4, 3], 3, 2, 3]

    # iterate over original list
    # if a list is encountered concatenate to sequence and delete said object.
    for x in seq:
        if isinstance(x,list):
            sequence += x
            del sequence[sequence.index(x)]
    print ("%r" % sequence)                  # [1, 2, 3, 3, 2, 3, 3, 4, 3]

    # iterate over flattened copy to count items
    counter = 0
    for x in sequence:
        if x == item:
            counter += 1
    return counter

balls = [3,4,3]
print(count([1,2,3, balls,3,2,3], 3))        # 5

#4

Thanks for the help, your answer makes a lot of sense, I didn't know about isinstance. I'm still a bit confused by the flattening process, though. It seems to me (from my next to zero knowledge of this stuff) that

sequence += x

would simply add the same list and create the same problem?

Why does

list = [1,2,3]
seq = [1, list, 3]
sequence = []
for x in seq:
        if isinstance(x,list):
            sequence += x

output [1,2,3] for sequence instead of just sequence = [list]?


#6

When we concatenate two lists we merge their elements.

[1, 2, 3] + [7, 8, 9]  => [1, 2, 3, 7, 8, 9]

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

[1, [1, 2, 3], 1]
[1, 1, 1, 2, 3]
3

#7

Gotcha, excellent, thanks for the help!


#8

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