Codon Usage Counter

Foundational Python Foundations Python Dictionaries Chunking Sorting
Significance:

Different organisms prefer different codons for the same amino acid, a phenomenon
called codon usage bias. Measuring it matters when designing genes for expression in a host organism —
a human gene expressed in E. coli often fails simply because it uses codons the bacterium reads slowly.
Counting codons is also the natural first use of a dictionary, which is the data structure biology code
reaches for most often.

Statement

Given a coding DNA sequence, split it into non-overlapping codons of three bases,
starting at position 0, and count how many times each codon appears.

Ignore any trailing bases that do not form a complete codon.

Print each distinct codon and its count on its own line, separated by a single space, sorted by count
descending. Where counts tie, sort by codon ascending lexicographically.

Input — read from standard input
Variable Type Description
cds
line 1
str The coding DNA sequence
3 <= len(cds) <= 3000, uppercase A, C, G, T only

These variables are already read for you in the starter code on the right.

Output

str one line per distinct codon, codon and count separated by a space, sorted by count desc then codon asc

Sample Cases
Sample 1
Input
ATGATGGCCTAA
Expected Output
ATG 2
GCC 1
TAA 1
ATG appears twice; GCC and TAA once each, broken by lexicographic order.
Sample 2
Input
AAACCC
Expected Output
AAA 1
CCC 1
Two distinct codons, one occurrence each.

Submit also runs your code against 4 hidden test cases. Hidden inputs are never shown — if one fails you'll get its number and a description of the mismatch, not the data.

Constraints
  • 3 <= length(cds) <= 3000
  • Codons are read in non-overlapping frames starting at position 0
  • Any trailing 1 or 2 bases are ignored
  • Sort by count descending, then by codon ascending — this makes output deterministic
Further Reading
  • range(0, len(cds) - 2, 3) walks the sequence in complete codons only.
  • A dict with .get(codon, 0) + 1 accumulates counts without needing to pre-populate keys.
  • Sort with a key such as (-count, codon) to get descending counts and ascending ties in one pass.

My Notes
Log in to save personal notes.
Console output will appear here when you click Run Code or Submit...
Expected: cds (str)
Next Problem
Trim Adapter Sequences