Warm-up 2
Last two characters
Write suffix(code) that returns the last two characters of a string that
has at least two characters.
suffix("BRD-001") -> "01"
def suffix(code):
...
Long name?
Write is_long(name) that returns True if the name has more than ten
characters.
is_long("sourdough bread") -> True
is_long("milk") -> False
def is_long(name):
...
Price with tax
Write with_tax(price) that returns the price plus 10% tax, rounded to two
decimal places.
with_tax(40) -> 44.0
with_tax(2.5) -> 2.75
with_tax(19.99) -> 21.99
def with_tax(price):
...
A line of dashes
Write rule(n) that returns a string of n dashes, for underlining a
receipt. rule(0) is the empty string.
rule(5) -> "-----"
def rule(n):
...
Items in order
prices maps item names to prices. Write item_names(prices) that returns
the item names as a list in alphabetical order.
item_names({"milk": 2.5, "apple": 40, "bread": 25}) -> ["apple", "bread", "milk"]
def item_names(prices):
...
Second cheapest
Write second_cheapest(prices) that returns the second smallest number in
a list of at least two different numbers.
second_cheapest([40, 2.5, 25]) -> 25
def second_cheapest(prices):
...
Everything but the first
Write rest(items) that returns a new list with everything except the
first item. For an empty list return an empty list.
rest(["apple", "bread", "milk"]) -> ["bread", "milk"]
rest([]) -> []
def rest(items):
...
Same items, any order
Two lists hold item names, possibly with repeats and in any order. Write
same_items(a, b) that returns True if they contain the same set of
distinct items.
same_items(["apple", "milk", "apple"], ["milk", "apple"]) -> True
same_items(["apple"], ["apple", "milk"]) -> False
def same_items(a, b):
...
Front of the line
Write next_customer(line) that returns the name at the front of a
deque, without removing it. The line is never empty.
next_customer(deque(["Ada", "Grace"])) -> "Ada"
from collections import deque
def next_customer(line):
...
Describe stock
Write describe(item, quantity) that returns the text <item>: <quantity> left.
describe("bread", 3) -> "bread: 3 left"
def describe(item, quantity):
...
Next: Warm-up 3.