I am solving the following HackerRank problem:
Consider a list (list = ). You can perform the following commands:
insert i e: Insert integer e at position i.
remove e: Delete the first occurrence of integer e.
append e: Insert integer e at the end of the list.
sort: Sort the list.
pop: Pop the last element from the list.
reverse: Reverse the list.
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.
My solution was:
if __name__ == '__main__': N = int(input()) my_list =  commands = dict( insert=lambda i,v: my_list.insert(i,v), print=lambda: print(my_list), remove=lambda e: my_list.remove(e), append=lambda v: my_list.append(v), sort=lambda: my_list.sort(), pop=lambda: my_list.pop(), reverse=lambda: my_list.reverse() ) for _ in range(N): command, *args = input().split() commands[command](*list(map(int, args)))
I did find another solution (I didn't write it) that seems cleaner than mine:
n = input() l =  for _ in range(n): s = raw_input().split() cmd = s args = s[1:] if cmd !="print": cmd += "("+ ",".join(args) +")" eval("l."+cmd) else: print l