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

View all comments

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.