Beginnerpuzzle3 tests
A dictionary maps keys to values. Use one whenever you need to look something up by name rather than by position.
depths = {"TP53": 120, "BRCA1": 88, "EGFR": 143}
print(depths["TP53"])
print(len(depths))
Reading safely
Indexing a missing key raises KeyError. get returns a default instead.
depths = {"TP53": 120}
print(depths.get("KRAS"))
print(depths.get("KRAS", 0))
print("KRAS" in depths)
Adding and updating
depths = {"TP53": 120}
depths["KRAS"] = 45
depths["TP53"] = 130
del depths["KRAS"]
print(depths)
Looping
depths = {"TP53": 120, "BRCA1": 88}
for gene in depths:
print(gene)
for gene, depth in depths.items():
print(gene, depth)
print(list(depths.keys()))
print(list(depths.values()))
Counting
A common pattern is counting occurrences. get with a default of 0 avoids a
separate check for the first time a key appears.
sequence = "ATGGCC"
counts = {}
for base in sequence:
counts[base] = counts.get(base, 0) + 1
print(counts)
Task
Write base_counts(sequence). Return a dictionary counting how many times each
of A, C, G and T appears. Include all four keys even when the count is 0, and
return them in the order A, C, G, T.
Test cases · 3
| # | via | input | expected stdout |
|---|---|---|---|
| 1 | stdin | ATGGCC | {'A': 1, 'C': 2, 'G': 2, 'T': 1} |
| 2 | stdin | AAAA | {'A': 4, 'C': 0, 'G': 0, 'T': 0} |
| 3 | stdin | GC | {'A': 0, 'C': 1, 'G': 1, 'T': 0} |
Hints · 2
01Hint
Start with a dictionary that already has all four keys set to 0.
02Hint
Insertion order is preserved, so build the dict in A, C, G, T order.