https://www.hackerrank.com/challenges/python-lists
主要是涉及到 getattr和eval, exec的应用
Task
You have to initialize your list L = [] and follow the NN commands given in NN lines.
Each command will be 11 of the 88 commands given above. The method extend(L) will not be used. Each command will have its own value(s) separated by a space.
For 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]
几种解法:
T = int(input().strip()) L = [] for t in range(T): args = raw_input().strip().split(" ") if args[0] == "print": print L elif len(args) == 3: getattr(L, args[0])(int(args[1]), int(args[2])) elif len(args) == 2: getattr(L, args[0])(int(args[1])) else: getattr(L, args[0])()
L = [] for _ in range(int(input())): command, *args = input().split() try: getattr(L, command)(*(int(x) for x in args)) except AttributeError: print(L)
n = input() L = [] for _ in range(n): s = input().split() cmd = s[0] args = s[1:] if cmd !="print": cmd += "("+ ",".join(args) +")" eval("L."+cmd) else: print (L)
T = int(input()) L = [] for i in range(T): commands = input().strip().split() if commands[0] == 'print': print(L) else: fullcommand = 'L.' + commands[0] + '(' + ','.join(commands[1:]) + ')' exec (fullcommand)