Warm-up 3
Price difference
Write difference(a, b) that returns how far apart two prices are, always
as a positive number (or zero).
difference(40, 25) -> 15
difference(25, 40) -> 15
def difference(a, b):
...
Even number?
Write is_even(n) that returns True if n is even.
is_even(4) -> True
is_even(7) -> False
def is_even(n):
...
Comma list
Write listing(items) that returns the items joined into one string
separated by a comma and a space.
listing(["apple", "bread", "milk"]) -> "apple, bread, milk"
listing([]) -> ""
def listing(items):
...
How many of this item?
Write how_many(basket, item) that returns how many times item appears
in the list basket.
how_many(["apple", "bread", "apple"], "apple") -> 2
how_many(["apple"], "milk") -> 0
def how_many(basket, item):
...
Cheapest price
prices maps item names to prices and is not empty. Write
cheapest_price(prices) that returns the lowest price.
cheapest_price({"apple": 40, "milk": 2.5, "bread": 25}) -> 2.5
def cheapest_price(prices):
...
Every other item
Write every_other(items) that returns a new list with the first item, the
third, the fifth, and so on.
every_other(["a", "b", "c", "d", "e"]) -> ["a", "c", "e"]
every_other([]) -> []
def every_other(items):
...
Swap a pair
Write swap(pair) that takes a tuple of two values and returns a tuple
with them the other way round.
swap(("bread", 25)) -> (25, "bread")
def swap(pair):
...
Smallest with a heap
Write smallest(nums) that returns the smallest number in a non-empty
list, without changing the list. min would do it; the point here is
practice with heapq. Remember that heapify rearranges the list it is
given, so if you use it, work on a copy.
smallest([40, 25, 2.5]) -> 2.5
import heapq
def smallest(nums):
...
Reverse the text
Write backwards(text) that returns the text reversed.
backwards("bread") -> "daerb"
def backwards(text):
...
Contains milk?
Write has_milk(order) that returns True if the letters milk appear
anywhere in the order text, in any mix of capitals. (So "milkshake"
counts too.)
has_milk("2 x Milk, 1 x bread") -> True
has_milk("bread") -> False
def has_milk(order):
...
Next: Standard 1.