It would be nice to just include the problem :) . The input is a (text) file as below:
Sample Input 0
12
insert 0 5
insert 1 10
insert 0 6
print
remove 6
append 9
append 1
sort
print
pop
reverse
print
And the expected output for a correct answer is as below:
Sample Output 0
[6, 5, 10]
[1, 5, 9, 10]
[9, 5, 1]
Before looking at the answer you quoted it would be good to read about eval; it takes the argument provided and tries to run it as a python expression using the global and local namespace. So in this case it needs only the local for the "l"
-list and "cmd"
-tuple.
What is happening is the following:
- Empty list l is created.
- The "command" (
cmd
) single-value list is parsed from the line by slicing (cmd = s[0]
), since every line starts with or only has a list method
- The other arguments are placed in
args
- Line 8 (as asked): These other arguments are then joined in a string tuple. So "insert 0 5" gives "insert" for
l
and "(0, 5)"
for cmd
- Line 8 continued (as asked):
cmd
is then combined with args
using string concatenation (read here for a good and bad example) resulting in "insert(0,5)" as value for cmd
- Line 9 (as asked): the eval parameter is yet another string concatenation yielding "l.insert(0,5)" as final expression to be interpreted. Which then inserts integer value
5
on spot 0 in list l
(pushing forward any other values already in l
)
Hope it helps, keep on trucking!