geeky_soham
geeky_soham

Reputation: 37

Cannot understand specific Python 3 code

While trying to solve a problem on Hackerank(The Problem). I checked the solutions of people who have solved this problem. Here is the solution from one person-

n = input()
l = []
for _ in range(n):
    s = raw_input().split()
    cmd = s[0]
    args = s[1:]
    if cmd !="print":
        cmd += "("+ ",".join(args) +")"
        eval("l."+cmd)
    else:
        print l

I cannot understand line 8 and line 9, can someone explain me these lines? Can i write line 8 and line 9 in Python 3 as i'm learning Python 3 ? How ?

Upvotes: 1

Views: 75

Answers (2)

MarcelTon
MarcelTon

Reputation: 177

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:

  1. Empty list l is created.
  2. 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
  3. The other arguments are placed in args
  4. 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
  5. 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
  6. 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!

Upvotes: 0

Reverse
Reverse

Reputation: 105

Basically, cmd is constructed by appending the command (say "insert"), to the operands. This cmd forms a correct python expression (for example l.insert(0,5), to insert 5 at index 0, in list l).

Here, l. is hardcoded(start of line 9), cmd is initialized in cmd = s[0], and operands are added in line 8.

eval(str) evaluates the command str, in string format, as if it were in a command line.

Upvotes: 1

Related Questions