Home > Back-end >  can you help ,e with the list of python?
can you help ,e with the list of python?

Time:01-11

Hi I'm a university student and I have to do a program. given a list of letters I have to say which is the length of the longest sequence. for example if I have the following list ["C", "A", "G", "G", "G", "T", "A", "C", "A", "A",] the solution that I have to find is the following 3, "G" as the G has been repeated 3 times in a row. could someone help me? thank you

i need for university

CodePudding user response:

You can use itertools.groupby

Link to doc : itertools.groupby

import itertools

lst = ["C", "A", "G", "G", "G", "T", "A", "C", "A", "A"]
result = []
for item, group in itertools.groupby(lst):
    count = sum(1 for _ in group)
    result.append((item,count),)

print(result)
#[('C', 1), ('A', 1), ('G', 3), ('T', 1), ('A', 1), ('C', 1), ('A', 2)]

#For maximum you can do:

m=max(result,key=lambda x:x[1])
#('G', 3)

m[0]
#'G'

CodePudding user response:

You could use a collection.Counter as following:

from collections import Counter

my_list = ["C", "A", "G", "G", "G", "T", "A", "C", "A", "A"]

counter = Counter(my_list)

Now you could print counter to see the ordered list:

print(counter)

And the result will be:

Counter({'A': 4, 'G': 3, 'C': 2, 'T': 1})

Or you can also query a specific key to know the get the count:

print(counter['G'])
  • Related