【hackrank】eval巧用,以命令操作列表
今天在hackrank看到一個關於列表的問題,比較有意思。
Python列表主要有以下幾種操作:
insert i e: Insert integerat position . print: Print the list. remove e: Delete the first occurrence of integer . append e: Insert integerat the end of the list. sort: Sort the list. pop: Pop the last element from the list. reverse: Reverse the list.
而想要實現,檢視下面樣例:
輸入:
12 insert 0 5 insert 1 10 insert 0 6 print remove 6 append 9 append 1 sort print pop reverse print
當讀者輸入接下來的命令數目,和對應命令後,你需要用Python對空列表做對應的事情,對應輸出為:
[6, 5, 10] [1, 5, 9, 10] [9, 5, 1]
比如第一個print
之前的命令:
- 在第一個位置插入5
- 在第二個位置插入 10
- 再在第一個位置插入6
所以第一個print
的結果為[6, 5, 10]
。
一般想到的辦法應當是,我們使用if
語句根據輸入的語句然後呼叫命令。但如果你仔細發現所謂的insert
,print
等命令其實在Python中有名字完全一致的方法或函式。能不能利用它?!
是可以的,我看到討論區有個Python2的解法後,略改一下就有了Python3的版本:
n = int(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)
在R語言裡也有一個eval
函式可以完成類似的功能,不同的是,Python直接可以計算字串,就是將字串解析為函式執行!當輸入命令為print
時呼叫函式,不是print
時直接呼叫列表的方法。