queenbegop777
queenbegop777

Reputation: 83

Counting elements that appear only one time in a matrix

I have a list:

l = [['a', []], ['b', []], ['c', []], ['d', ['c']], ['e', ['d']], ['f', []], ['g', ['f', 'a', 'e']], ['h', ['g']]]

I want to count how many times an element doesn't appear in another list, for example in this list it would be b and h.

These are the only elements that appear only one time in all the list , so the function would return 2.

Another example:

l2 = [['a', []], ['b', []], ['c', ['b']], ['d', ['c', 'b', 'a']], ['f', ['d']], ['g', ['f', 'a']], ['h', ['f', 'c']], ['i', ['h', 'a']]]

Here we got 2 elements that appear only one time in all the lists: g and i

I want to use the python function count but I don't really know how to apply it in this case.

Upvotes: 0

Views: 151

Answers (2)

Anass ABEA
Anass ABEA

Reputation: 479

Hello based on what you requested I have made a function that I called count(matrix) it returns an array of char that exist once in the matrix provided as a paramter

def count(matrix):
    result=[]
    removed= []
    for line in matrix:
        if line[0] in result :
            result.remove(line[0])
        elif line[0] not in removed:
            result.append(line[0])
            removed.append(line[0])
        for e in line[1]:
            if e in result :
                result.remove(e)
            
            elif e not in removed:
                result.append(e)
                removed.append(e)
    return result

Hope this was useful

Upvotes: 1

qmorgan
qmorgan

Reputation: 85

n contains the elements that appear only once

l = [['a', []], ['b', []], ['c', []], ['d', ['c']], ['e', ['d']], ['f', []], ['g', ['f', 'a', 'e']], ['h', ['g']]]
m = []
n = []
counter = []

for i in l:
    m.append(i[0])

    for j in i[1]:
        m.append(j)

m.sort()

for i in m:
    count = 0
    for j in m:
        if i == j:
            count += 1
    counter.append(count)

n = [m[i] for i in range(0,len(m)) if counter[i] == 1]

Upvotes: 1

Related Questions