Beginnerpuzzle2 tests
A list is an ordered, changeable sequence of values. Lists hold anything, and are the default container for a collection of records.
genes = ["TP53", "BRCA1", "EGFR"]
print(genes[0])
print(genes[-1])
print(len(genes))
Changing a list
genes = ["TP53", "BRCA1"]
genes.append("EGFR")
genes.insert(0, "KRAS")
genes.remove("BRCA1")
print(genes)
popped = genes.pop()
print(popped, genes)
Sorting
sort() changes the list in place and returns None. sorted() returns a new
list and leaves the original alone.
depths = [30, 12, 45, 7]
print(sorted(depths))
print(sorted(depths, reverse=True))
print(depths)
depths.sort()
print(depths)
Sort by something other than the value itself with key:
genes = ["TP53", "BRCA1", "EGFR"]
print(sorted(genes, key=len))
Slicing returns a copy
depths = [30, 12, 45, 7]
first_two = depths[:2]
first_two[0] = 999
print(depths[0])
Assigning a list to a second name does not copy it. Both names refer to the same list.
a = [1, 2, 3]
b = a
b.append(4)
print(a)
Use a.copy() or a[:] when you need an independent list.
Task
Write top_n(values, n). It receives a list of integers and returns the n
largest, in descending order, as a list. Do not modify the input list.
Test cases · 2
| # | via | input | expected stdout |
|---|---|---|---|
| 1 | stdin | 30 12 45 7 88 3 | [88, 45, 30] |
| 2 | stdin | 5 5 5 2 | [5, 5] |
Hints · 2
01Hint
sorted(values, reverse=True) returns a new list.
02Hint
Slice the first n items off the sorted result.