[Solved] How to create a function that counts the number of twos in a list? [closed]


This function M will count groups of a value. It outputs a list of group occurrences in this format: [index of group, length of group].

It uses a flag m to keep track of in/out of group. If it’s out, it starts a new group occurrence, if it’s in, it increments the group length. It goes down the list and tests equality of the value.

t=[2,2,3,3,3,4,3,4,2,2,2,2,2]
j=[2,2,2,3,4,5,6,7,5,4,2,2,4,5,2]

def M(L, N):
    c = []
    m = 0
    for i,n in enumerate(L):
        if n == N:
            if m:
                c[-1][1] += 1
            else:
                c.append([i, 1])
            m = 1
        else:
            m = 0
    return c

print M(t, 2)
print M(j, 2)

Output:

[[0, 2], [8, 5]]
[[0, 3], [10, 2], [14, 1]]

0

solved How to create a function that counts the number of twos in a list? [closed]