Home > Software design >  find the lengths of all sublists containing common repeated element
find the lengths of all sublists containing common repeated element

Time:08-14

I need to find all the sublists from a list where the element is 'F' and that must come one after other

g= ['T','F','F,'F','F','T','T','T','F,'F','F','T]

so, here in this case there are two sublists present in this list which contains element 'F' in repeat

i.e; ['F','F,'F','F'] in index 1,2,3,4 which is in repeat ,so answer is 4
and
['F','F,'F'] in index 8,9,10 which is again in continuous index,so answer is 3

Note: The list contains only two elements 'T' and 'F' and every time we are doing these operations for element 'F'

CodePudding user response:

You can get the lengths of consecutive sequences with itertools.groupby:

from itertools import groupby

data = ['T','F','F','F','F','T','T','T','F','F','F','T']

# Consecutive sequences of "F".
#   "groupby(data)" produces an iterator that calculates on-the-fly.
#   The iterator returns consecutive keys and groups from the iterable "data".
seqs = [list(g) for k, g in groupby(data) if k == 'F']
print(seqs)
# [['F', 'F', 'F', 'F'], ['F', 'F', 'F']]
seq_lens = [len(k) for k in seqs]
print(seq_lens)
# [4, 3]

Also cool is max length of such consecutive sequences:

max_len_seq = len(max(seqs, key=len))
print(max_len_seq)
# 4

See itertools.groupby for more info:

class groupby:
    # [k for k, g in groupby('AAAABBBCCDAABBB')] --> A B C D A B
    # [list(g) for k, g in groupby('AAAABBBCCD')] --> AAAA BBB CC D
    ...
    etc

CodePudding user response:

You can create 2 variable to keep count of the repeated letter. Traverse the array and when you found t increase t, when you find a f check the tcount first if it is bigger than 1 it means there is a repeat print the count of the repetition.

tcount = 0;
fcount = 0;
for e in g:
   if e=="T":
      tcount  
      if fcount>1
         print(fcount)
      fcount=0
  //do same operation for F
  • Related