-2

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

  • 4
    What you actually "need" is to figure out how to do this on your own. That's what University is for. – Mark Ransom Jan 10 '23 at 14:01
  • Show your solution attempts. What are the problems? – Denis Artyushin Jan 10 '23 at 14:01
  • 1
    Have you tried thinking about how you are going to solve it? Take a piece of paper and scribble down the steps that you would do to solve this problem. Then translate that to code. – TheFlyingObject Jan 10 '23 at 14:01
  • 1
    Does this answer your question? [Finding consecutively repeating strings in Python list](https://stackoverflow.com/questions/25438491/finding-consecutively-repeating-strings-in-python-list) – NelsonGon Jan 10 '23 at 14:25

2 Answers2

0

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'
Talha Tayyab
  • 8,111
  • 25
  • 27
  • 44
-2

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'])
tomasborrella
  • 480
  • 2
  • 8
  • This does not account for repetitions as I understood it. Say, one G is out of the sequence, this would still count all occurrences of G, not if they are in their order e.g. `["C", "A", "G", "G", "G", "T", "A", "C", "A", "A","G"]` – NelsonGon Jan 10 '23 at 14:10
  • 1
    It's best not to answer obvious assignment questions where the poster has obviously not even tried to solve it themselves. – joanis Jan 10 '23 at 14:10
  • You are both right! @NelsonGon, I read the question too fast. My mistake. – tomasborrella Jan 10 '23 at 14:19
  • 1
    @joanis, I will try not to answer any more questions when it is so obvious that there has not been enough effort. Thanks both – tomasborrella Jan 10 '23 at 14:19