【hackrank】eval巧用,以命令操作列表

今天在hackrank看到一个关于列表的问题,比较有意思。

Python列表主要有以下几种操作:

insert i e: Insert integer  at position .
print: Print the list.
remove e: Delete the first occurrence of integer .
append e: Insert integer  at 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语句根据输入的语句然后调用命令。但如果你仔细发现所谓的insertprint等命令其实在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时直接调用列表的方法。

点赞