-1

The code is from an UVA. It goes like:

Consider a list (list = []). You can perform the following commands:

 insert, print, remove, append, sort, pop, reverse.

Initialize your list and read in the value of followed by lines of commands where each command will be of the types listed above. Iterate through each command in order and perform the corresponding operation on your list.

Inputs: The first line contains an integer, denoting the number of commands. Each line of the subsequent lines contains one of the following commands.

Sample Input

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

Sample Output

[6, 5, 10]
[1, 5, 9, 10]
[9, 5, 1]

A neat solution I found is:

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 don't really understand how the part " ("+ ",".join(args) +") " works. Especially why the + in the beginning and at the end. An explanation would be great. Thanks.

Rio1210
  • 238
  • 1
  • 4
  • 13

1 Answers1

0

.split will divide your your string into an array. Each space will create a new element, so if you have "I like food", it will become ["I","like","food"]. Now we can look at our .join. The .join is doing the reverse. So if we were to call ','.join(["I","like","food"]), we'd get "I,like,food". In your function, we are using .join to combine a series of list elements into a series of string arguments, then we invoke eval and it executes.

And, eval is not recommended. So, instead, we can write a chain for if and elif statements:

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

li = []

for line in inpu.split("\n"):
    args = line.split()
    if args[0] == "insert":
        li.insert(int(args[1]),int(args[2]))
    elif args[0] == "print":
        print(li)
    elif args[0] == "remove":
        li.remove(int(args[1]))
    elif args[0] == "sort":
        li.sort()
    elif args[0] == "reverse":
        li = li[::-1]
    elif args[0] == "append":
        li.append(int(args[1]))
    elif args[0] == "pop":
        li.pop()
Neil
  • 14,063
  • 3
  • 30
  • 51