Task
You have to
initialize your list L = [] and follow the N commands given in N
lines.
Commands will be 1
of the 8 commands as given above, other than extend, and each command
will have its value separated by space.
Follow this example:
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]
Python Code
Solution 1 -
#!/usr/bin/python
lst = []
n = int(raw_input())
#Loop till all the
commands are read
for i in range(0,n):
read =
raw_input()
cmd =
read.split()
#check for
the commands and perform the action
if (cmd[0]
== 'insert'):
lst.insert(int(cmd[1]),int(cmd[2])) #pos,elem
elif(cmd[0]
== 'print'):
print lst
elif(cmd[0]
== 'remove'):
lst.remove(int(cmd[1]))
elif(cmd[0]
== 'append'):
lst.append(int(cmd[1]))
elif(cmd[0]
== 'sort'):
lst.sort()
elif(cmd[0]
== 'pop'):
lst.pop()
elif(cmd[0]
== 'reverse'):
lst.reverse()
elif(cmd[0]
== 'count'):
lst.count(int(cmd[1]))
elif(cmd[0]
== 'index'):
lst.index(int(cmd[1]))
Solution 2 -
n = input()
l = []
for _ in range(n):
read =
raw_input().split()
cmd =
read[0]
args =
read[1:]
if cmd
!="print":
cmd
+= "(" + ",".join(args) + ")"
eval("l."+cmd)
else:
print l
Comments