r/learnpython • • Sep 22 '26

Help with an online question from datadaily.io

I keep getting this one wrong but my answer is right as far as i can tell

The Molecule Report

Asked inInvitae

A genomics pipeline hands you raw sequencing reads as strings over the bases A, C, G, and T, and some reads come back contaminated with stray characters. For each read return a dict reporting whether it is clean (only those four bases), its GC content as a percentage of the read's length, how many times each of the four bases occurs, and the most common pair of consecutive bases. A read shorter than two bases has no such pair, so that field comes back empty.

Example 1

Input
sequence:"ATGCATGC"
Output{
  "is_valid": true,
  "gc_content": 50,
  "nucleotide_counts": {"A":2,"C":2,"G":2,"T":2},
  "most_common_dinucleotide": "TG"
}

Example 2

Input
sequence:"AAAT"
Output{
  "is_valid": true,
  "gc_content": 0,
  "nucleotide_counts": {"A":3,"C":0,"G":0,"T":1},
  "most_common_dinucleotide": "AA"
}


My code:

def analyze_dna_sequence(sequence: str) -> dict:
  mydict={}
  smalldict={"A": 0,
    "C": 0,
    "G": 0,
    "T": 0
    }
  mydict["is_valid"] = all(char in "ACGT" for char in sequence)
  for nucleotide in sequence:
    try:
      smalldict[nucleotide] += 1
    except KeyError:
      pass
  mydict["gc_content"] = ((smalldict["G"] + smalldict["C"]) / sum(smalldict.values())) * 100 if sum(smalldict.values()) > 0 else 0
  mydict["nucleotide_counts"] = smalldict
  
  mydict["most_common_dinucleotide"] = max(set(pairs := [a + b for a, b in zip(sequence, sequence[1:])]), key=pairs.count) if len(sequence) >= 2 else ""

return mydict

Error:

Failed Test Case (1 of 6)

Input

{"sequence":"ATGCATGC"}

Expected

{"is_valid":true,"gc_content":50,"nucleotide_counts":{"A":2,"C":2,"G":2,"T":2},"most_common_dinucleotide":"TG"}<

Your Output

{"is_valid":true,"gc_content":50,"nucleotide_counts":{"A":2,"C":2,"G":2,"T":2},"most_common_dinucleotide":"AT"}<

The issue is that the marking scale only recognises one dinucleotide pair as the most common- GC. But there are 3 in that sequence- AT, TG, and GC. Am i going insane here or is it the question that is wrong?
0 Upvotes

10 comments sorted by

2

u/backfire10z Sep 22 '26 edited Sep 22 '26

If you’ve copied the question in its entirety, then yeah, I have the same confusion as you. There’s no tie breaker.

Your code works, but is inefficient. You go over the sequence many times. One easier optimization: can you utilize the key error for smalldict to determine if the sequence is valid?

1

u/TheCrappler Sep 22 '26

The question is copied in its entirety. And yes, I currently suck at python

2

u/smurpes Sep 22 '26 edited Sep 22 '26

Your code is pretty good. The issue is just an annoying way of handling ties when aggregating. The approach here solves the issue by also ranking by the value so it’s alphabetically ranked when there’s a tie. The set is unnecessary though.

1

u/backfire10z Sep 22 '26

Haha no worries. Everybody is bad at the start. The other guy may be onto something about (reverse?) lexicographical order.

1

u/kyle2143 Sep 22 '26

Yeah, without reading your code, I can't tell why the first example would only accept "TG" as the output over any of the other valid ones ("AT" and "GC")...

Seems like they randomly chose "TG" out of those options based on however they decided to write their version of the solution. If they chose "AT", I would have suggested that you just default to the first one that was detected, but they chose the second one. 

Either that, or there's some sort of domain knowledge about nucleotide sequencing that you're expected to know.

1

u/TheCrappler Sep 22 '26

It cant be that. Im an ex molecular biologist; its why i chose this question

2

u/EntrepreneurHuge5008 Sep 22 '26 edited Sep 22 '26
The issue is that the marking scale only recognises one dinucleotide pair as the most common

The issue is that the question didn't define a tiebreaker.

Edit: Looks like it might be doing it in lexicographical order, "TG" is lexicographically larger than AT and GC. You'd probably want to change your key=pairs.count into a lambda:

key=lambda x: (pairs.count(x), x)

Or something like that so it compares the string directly when there are count ties.

1

u/ekchew Sep 22 '26

There may be an issue with your code. It seems like you want to count up these dinucleotide pairs just as you did with the single nucleotides in smalldict, but that expression you have there after mydict["most_common_dinucleotide"] = is not doing so.

Though you could do this with a regular dict, it's probably easier if you import defaultdict from collections. Then you can go:

smalldict2 = defaultdict(lambda: 0)
for a, b in zip(sequence[:-1], sequence[1:]):
    smalldict2[a + b] += 1

(What defaultdict does is if the key is not already in smalldict2, it adds a new item with that key and an initial value of 0. Then the increment by 1 happens.)

At this point, the dict should contain:

{'AT': 2, 'TG': 2, 'GC': 2, 'CA': 1}

So then you just need the pair with the highest count. But there appear to be 3 that appear twice, so I think you're right that the question is wack. There's no single correct solution unless I'm misunderstanding genetics.

3

u/smurpes Sep 22 '26

OPs implementation is correct but the answer wants the max in terms of lexicographical ordering as well as count. The problem is that the ordering of a set is by hash and can change and max will return the first value in order of its position when there’s a tie.

Using a default dict to get a count is not needed especially with the counter function in collections. With the default dict approach you would need to pass it through the max function keyed on the values anyways.

1

u/ekchew Sep 22 '26

Ah ok, thanks. I'll have a look at how those counters work.