0

I was suggested the below solution but I didn't understand this line cmd += "("+ ",".join(args) +")" of the below code. I got frustated because of this.Can someone please help me

Question is Reading an input like this

12
insert 0 5
insert 1 10
insert 0 6
print 
remove 6
append 9
append 1
sort 
print
pop
reverse
print

My arttempt in Python language

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
the
  • 21,007
  • 11
  • 68
  • 101
Dhrub kumar
  • 71
  • 2
  • 7

3 Answers3

2

This line is there to ensure that your command is in the right syntax and has brackets and comma when you call it! I wrote it clearer in the code below:

cmd = 'insert'
arg1 = '1'
arg2 = '3'
arg3 = '10'

cmd = cmd + "(" + ",".join((arg1, arg2, arg3)) + ")"
print cmd

Output:

insert(1,3,10)
Blind0ne
  • 1,015
  • 12
  • 28
1

Consider the following input line:

insert 1 10

So s is the list ["insert", "1", "10"]. Note that the list elements are all strings.

So cmd is "insert" and args is ["1", "10"].

Now here's the part that you didn't understand. First, ",".join(args) just creates a single string composed of the elements of arg, separated by commas: "1,10".

This is then wrapped in parentheses: "(1,10)". Finally, it is appended to cmd resulting in the string "insert(1,10)".

It then prepends "l." to this, resulting in the string "l.insert(1,10)". This is then passed to eval.

So it's invoking the insert method on the list l, inserting the value 10 at position 1. I.e., it's executing l.insert(1,10).

Tom Karzes
  • 22,815
  • 2
  • 22
  • 41
1

Your question is what does the following line mean:

cmd += "("+ ",".join(args) +")"

cmd is a variable (with a string).

+= is an operator which adds the right side to the left side.

"(" is a string containing a left parens.

+ is an operator that adds the left and right of itself.

",".join(args) this makes the list, args, into a string separated by commas. For example:

args =['bob','sue','tom'], then: 
",".join(args)
> bob,sue,tom

again, + is an operator that adds the left and right of itself.

) is a string containing a right parens.

Thus, if args is ['bob',sue','tom], and cmd is names, then the output of this line would be:

cmd = "names"
args =["bob","sue","tom"]
cmd += "("+ ",".join(args) +")"
print cmd
> names(bob,sue,tom)
AbrahamB
  • 1,348
  • 8
  • 13