Command lists: parse and respond
Many questions hand you a list of command strings like "ADD pen 3" and ask for the outputs. The pattern:
for cmd in commands: parts = cmd.split() # ["ADD", "pen", "3"] word = parts[0]
split()with no argument handles extra spaces for you.- Convert numbers with
int(parts[2])only after you know the command has that many parts. - Keep state in a dict (balances, stock) and an outputs list that you fill as the statement says. Decide whether every command produces an output or only some do.
- The statement defines the invalid cases (unknown word, wrong word count, bad number, not enough money). Each one has an exact response, so write that rule down first.
In the visual, watch parts and stock change as each command is read; the SHOW command is ignored because no branch handles it.
See it run
stock = {}
for cmd in ["ADD pen 3", "ADD pen 2", "SHOW pen"]:
parts = cmd.split()
if parts[0] == "ADD":
stock[parts[1]] = stock.get(parts[1], 0) + int(parts[2])
print(stock)Each command string is split into words, then the first word decides what to do.
Practice command lists: parse and respond
Exercise 1
A shop processes commands, each a string of words separated by spaces. Stock starts empty (every item has 0).
"ADD item n": stock ofitemgoes up byn."REMOVE item n": stock ofitemgoes down byn, but never below 0."COUNT item": adds the current stock ofitemto the output (0 if the item was never added).- Any other command is ignored.
Item names have no spaces and are case-sensitive; n is a positive integer. Return the list of outputs, one integer per COUNT, in order.
Constraints: 0 ≤ len(commands) ≤ 10^4.
Example: solution(["ADD pen 3", "ADD pen 2", "COUNT pen"]) returns [5].
Exercise 2
A bank handles commands (strings of words separated by spaces; extra spaces anywhere are ignored). Account balances start at 0 for every name. Amounts must be a positive whole number written with digits only (so "0", "-3", "2.5" and "x" are invalid).
"DEPOSIT name amt": addsamttoname. Output"OK"."WITHDRAW name amt": if the balance is at leastamt, subtract it and output"OK"; otherwise change nothing and output"DENIED"."TRANSFER from to amt": iffromandtoare the same name, output"ERR". Otherwise, iffromhas at leastamt, move it and output"OK"; else change nothing and output"DENIED"."BALANCE name": output the balance as a string ("0"for a name never used; asking does not create the account).- Anything else is invalid and outputs
"ERR"with no change: an empty command, an unknown or lowercase command word, the wrong number of words for that command, or an invalid amount. ERR takes priority over DENIED.
Return the list with one output string per command.
Constraints: 0 ≤ len(commands) ≤ 10^4.
Example: solution(["DEPOSIT ann 50", "WITHDRAW ann 20", "BALANCE ann"]) returns ["OK", "OK", "30"].
Exercise 3
A key-value store handles commands (words separated by spaces; keys and values have no spaces). Keys start unset.
"SET k v": sets keykto the textv."DELETE k": unsetsk(nothing happens if it was not set)."GET k": adds the value ofkto the output, or the text"NULL"if unset."BEGIN": opens a transaction. Transactions can be nested."ROLLBACK": undoes every SET and DELETE made since the innermost open BEGIN, and closes it."COMMIT": closes the innermost open transaction and keeps its changes (an outer ROLLBACK can still undo them).ROLLBACKorCOMMITwith no transaction open adds"NO TRANSACTION"to the output and changes nothing.- Any other command is ignored. Only GET and the NO TRANSACTION cases add to the output.
Return the list of output strings.
Constraints: 0 ≤ len(commands) ≤ 10^4.
Example: solution(["SET a 1", "BEGIN", "SET a 2", "GET a", "ROLLBACK", "GET a"]) returns ["2", "1"].
The explanation and tasks are public. Running this lesson requires an account with course access.
Practice
Loading Python…Visualizer Watch your code run line by line
Run your code, then choose Play to follow its execution.