Price Lookup
A price list is given as lines like "apple=1.50". Write price_lookup(lines) that returns a dictionary from the item name to its price as a float.
- Lines that have no
=, or whose price is not a number, are skipped. - If an item appears more than once, the last price wins.
- Spaces around the name and the price are ignored.
Understand the problem
Look at the building blocks.
What does "apple=1.50".partition("=") return?
["apple", "1.50"]("apple", "=", "1.50")("apple", "1.50")
partition always returns a tuple of three: the part before the separator, the separator, and the part after. If the separator is missing, you get (text, "", ""), which makes it easy to detect a bad line.
What does float("1.5x") do?
- Returns
1.5 - Raises
ValueError - Returns
0.0
float raises a ValueError when the text is not a number. To skip bad lines you need try / except ValueError (a comprehension cannot contain try, so a small helper function or a loop is needed).
Write the solution
Return the dictionary.
def price_lookup(lines):
# Write your code here.
pass
Hint 1: a question to ask yourself
How do you tell a good line from a bad one, and where do you put the try / except?
Hint 2: the shape of the answer
A loop over the lines. Use partition("="). If the separator is empty, continue. Try float(price); on ValueError, continue. Otherwise prices[name.strip()] = value.
Reflect
Solution
def price_lookup(lines):
prices = {}
for line in lines:
name, separator, price = line.partition("=")
if not separator:
continue
try:
prices[name.strip()] = float(price)
except ValueError:
continue
return prices
Another way: a helper and a comprehension
def _parse(line):
name, separator, price = line.partition("=")
try:
return (name.strip(), float(price)) if separator else None
except ValueError:
return None
def price_lookup(lines):
return dict(pair for pair in map(_parse, lines) if pair)
What this tests: str.partition, try / except for bad data, continue, and the later-wins behaviour of dictionary assignment.
Why not a single comprehension? A comprehension cannot contain try. When the parsing can fail, put it into a small helper function that returns None on failure, and filter the None out. Never force everything into one line.
float ignores spaces (float(" 1.5 ") is 1.5), but names need strip().
Cost: O(n).
What an interviewer might ask next: How would you report the skipped lines? (Collect their numbers in a second list and return both: a pattern from the Errors chapter.)
VISIBLE = 3
CASES = [
((['apple=1.50', 'bean=0.25'],), {'apple': 1.5, 'bean': 0.25}, 'two good lines'),
((['apple=1.50', 'bad line', 'fig=x'],), {'apple': 1.5}, 'bad lines are skipped'),
(([],), {}, 'no lines'),
((['a=1', 'a=2'],), {'a': 2.0}, 'the last price wins'),
(([' milk = 2.25 '],), {'milk': 2.25}, 'spaces are ignored'),
((['x='],), {}, 'a missing price'),
((['=5'],), {'': 5.0}, 'an empty name is still a name'),
((['tea=3', 'tea=nope'],), {'tea': 3.0}, 'a later bad line does not remove an earlier price'),
((['k=1=2'],), {}, 'the price is not a number'),
]