Loops
A for statement iterates over the elements of a sequence, binding each element
to a name in turn and executing the body once per element. Python's for is a
sequence iteration construct rather than a counter, so it applies directly to
lists, strings, dictionaries and files without an index variable.
TP53 BRCA1 EGFR
range
range produces a sequence of integers. range(stop) counts from 0;
range(start, stop) counts from start; range(start, stop, step) advances by
step. The stop value is excluded, consistent with slicing, so range(3)
yields 0, 1 and 2.
[0, 1, 2] [0, 3, 6]
Stepping by three walks a coding sequence codon by codon. Combined with slicing, this extracts each codon without an index arithmetic error.
0 ATG 3 GCC 6 ATT 9 GTA
enumerate and zip
When both the element and its position are required, enumerate supplies both
and avoids maintaining a separate counter. Its start argument sets the first
index, which is useful when reporting one-based line numbers.
zip iterates over several sequences in parallel, stopping when the shortest is
exhausted.
1 TP53 2 BRCA1 TP53 120 BRCA1 88
Controlling the loop
break terminates the loop immediately. continue skips the remainder of the
current iteration and proceeds to the next element. A loop may also carry an
else block, which executes only if the loop completed without encountering
break. This structure is useful when searching for an element and needing to distinguish
between finding a target and exhausting the sequence.
kept 30 kept 45 no depth above 40
while
A while statement repeats for as long as its condition holds. Use it when the
number of iterations is not known in advance. The condition must be able to
become false, and something in the body must affect it, or the loop will not
terminate.
-1 3
Modifying while iterating
Adding to or removing from a list while iterating over it produces skipped elements or a runtime error, because the iterator's position no longer matches the list. Build a new list instead, or iterate over a copy.
Task
Write codons(sequence). Split the sequence into three-character codons and
return them as a list. Any trailing one or two characters that do not form a
complete codon are discarded.
A slice that extends past the end of a string is silently truncated rather than raising, so the length of each slice must be checked before it is kept.
Test cases · 3
| # | via | input | expected stdout |
|---|---|---|---|
| 1 | stdin | ATGGCCATT | ['ATG', 'GCC', 'ATT'] |
| 2 | stdin | ATGGCCAT | ['ATG', 'GCC'] |
| 3 | stdin | AT | [] |
Hints · 2
01Hint
range(0, len(sequence), 3) gives each codon start position.
02Hint
A slice past the end is short, so check its length before keeping it.