Standard 2
Dearest item
items is a non-empty list of (name, price) tuples. Write
dearest(items) that returns the name of the most expensive one.
dearest([("milk", 2.5), ("apple", 40), ("bread", 25)]) -> "apple"
def dearest(items):
...
Running total
Write running(amounts) that returns a list where each position holds the
sum of all amounts up to and including that one.
running([10, 5, 20]) -> [10, 15, 35]
running([]) -> []
def running(amounts):
...
Split a product code
Product codes look like BRD-001-A: department, number and batch separated
by dashes. Write parts(code) that returns the three pieces as a tuple.
parts("BRD-001-A") -> ("BRD", "001", "A")
def parts(code):
...
Pop several
Write pop_n(stack, n) that pops up to n items off a stack (a list) and
returns them as a list in the order they were popped. Stop early if the
stack runs out.
pop_n(["a", "b", "c"], 2) -> ["c", "b"] (stack is now ["a"])
pop_n(["a"], 3) -> ["a"]
def pop_n(stack, n):
...
Discounted total
Orders of 100 or more get 20% off, orders of 50 or more get 10% off, smaller
orders pay full price. Write to_pay(total) that returns the amount to pay,
rounded to two decimal places.
to_pay(120) -> 96.0
to_pay(60) -> 54.0
to_pay(77.77) -> 69.99
to_pay(20) -> 20 (20.0 is fine too)
def to_pay(total):
...
Codes to names
codes maps item names to product codes, and no two items share a code.
Write by_code(codes) that returns the reverse mapping, from code to name.
by_code({"bread": "BRD-001", "milk": "MLK-010"}) -> {"BRD-001": "bread", "MLK-010": "milk"}
def by_code(codes):
...
Word counts
Write word_counts(text) that returns a dictionary of how many times each
word appears, treating capitals and lowercase as the same word.
word_counts("Bread and milk and bread") -> {"bread": 2, "and": 2, "milk": 1}
def word_counts(text):
...
Common prefix
Write common_prefix(a, b) that returns the longest string that both a
and b start with.
common_prefix("sourdough", "soup") -> "sou"
common_prefix("milk", "bread") -> ""
def common_prefix(a, b):
...
Two largest
Write top_two(prices) that returns the two largest values from a list of
at least two, largest first, using heapq. A repeated value counts each
time it appears.
top_two([40, 25, 2.5, 60]) -> [60, 40]
top_two([5, 5, 1]) -> [5, 5]
import heapq
def top_two(prices):
...
Pair them up
Write pairs(items) that groups a list with an even number of items into
consecutive pairs, as a list of tuples.
pairs(["a", "b", "c", "d"]) -> [("a", "b"), ("c", "d")]
pairs([]) -> []
def pairs(items):
...
Next: Standard 3.