Asked at Wolverine Trading, Marshall Wace
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.
Available in Python and C++. You are solving it in Python. Switch to C++
Implement parse_order(s), a parser for order shorthand. 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. The parser never guesses: anything that does not match the
grammar exactly is rejected, not repaired.
Desks still pass orders around in this shorthand, in chat, in test fixtures and in legacy tools.
parse_order returns four values: side, which is "BUY"
or "SELL"; qty, an integer; symbol, the string; and price, which is
absent for a market order. If s is invalid, return nothing at all (the whole
result, not a field).
def parse_order(s: str) -> tuple[str, int, str, float | None] | None: ...
A valid string returns the tuple (side, qty, symbol, price) with price a
float, or None for a market order. An invalid string returns None.
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 (a market order, with no price), 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 has length at most 100; a single pass is plenty.@, trailing
characters) must also be rejected.