Asked at Wolverine Trading
Theory: Parsing and Data HygieneRead the problem, hints and solution here. The editor needs a bigger screen: open this page on a laptop to write and run your code.
Desks still pass orders around in a compact shorthand, in chat, in test
fixtures, in the odd legacy tool: B 100 AAPL @ 152.35 means buy 100
shares of AAPL at 152.35, and S 50 TSLA @ MKT means sell 50 TSLA at
market. A parser for order shorthand has one job above all others: never
guess. Anything that does not match the grammar exactly is rejected, not
repaired.
Implement parse_order(s) returning the tuple
(side, qty, symbol, price) where side is "BUY" or "SELL", qty an
int, symbol the string, and price a float, or None for a market
order. Return None (the whole result, not a field) if s is invalid.
A valid string is exactly five fields separated by single spaces, with
no leading or trailing whitespace: SIDE QTY SYMBOL @ PRICE.
SIDE: exactly B or S (case-sensitive; BUY or b are invalid).QTY: one or more digits, no leading zero, value greater than 0.SYMBOL: 1 to 6 uppercase letters A-Z only.@.PRICE: either exactly MKT (price becomes None), or one or more
digits optionally followed by . and one or two decimal digits, with
numeric value strictly greater than 0. So 152.35, 7 and 0.50 are
valid; .35, 152., 152.345, 0 and 0.00 are not.parse_order("B 100 AAPL @ 152.35")
# ('BUY', 100, 'AAPL', 152.35)
parse_order("S 50 TSLA @ MKT")
# ('SELL', 50, 'TSLA', None)
(parse_order("B 100 aapl @ 152.35"), parse_order("S 5 MSFT @ 401.10"))
# (None, ('SELL', 5, 'MSFT', 401.1))
# a lowercase symbol is invalid; note 401.10 parses to the float 401.1
s is a str of length at most 100; a single pass is plenty.@, trailing
characters) must also return None.Run your code to check it against the sample tests. Results appear here.