当我试图解决黑客等级的问题时,(problem link)。 我对set有问题。在python中,set不支持重复。所以,我需要另一种选择。我使用的代码是:
n = int(input())
global rule_set, semifinal_list, final_list, name
rule_set = {}
semifinal_list = []
final_list = []
name = []
for _ in range(n):
rule,*no = input().split()
name.append(rule)
condition = list(map(int, no))
rule_set[rule] = condition
def cal(n):
for i in name:
print(name)
if (i == "insert"):
insert = rule_set["insert"]
semifinal_list.insert(insert[0],insert[1])
print(semifinal_list)
elif(i == "append"):
append = rule_set["append"]
semifinal_list.append(append)
elif(i == "remove"):
remove = rule_set["remove"]
semifinal_list.remove(remove)
elif(i == "pop"):
pop = rule_set[pop]
semifinal_list.pop(pop)
elif(i == "sort"):
semifinal_list.sort()
elif(i == "reverse"):
semifinal_list.reverse
elif(i == "print"):
def removenesting(semifinal_list):
for i in semifinal_list:
if (type(i) == list):
removenesting(i)
else:
final_list.append(i)
removenesting(semifinal_list)
print(final_list)
cal(n)
这里,rule_set{}
是我有问题的集合。我需要给出几个输入,比如
12
insert 0 5
insert 1 10
insert 0 6
print
remove 6
append 9
append 1
sort
print
pop
reverse
print
,但该集合不支持重复。我需要一个替代品。即使你知道解决这个问题的任何其他简单方法,也要用完整的解释来重播
所以,看看这个问题和你的解决方案,它看起来可以缩短很多。 以下是我的解决方案:
另外,我不使用HackerRank,所以我不知道它是否能在所有条件下运行,但它在基本情况下确实能运行
说明:
.join()用一个左括号“(”)连接ls,用逗号连接参数,然后连接一个右括号
eval解析传递给此方法的表达式并运行它。这里,它获取列表
l
,并添加需要执行的函数。 例如:附加6:
eval("l." + ls)
将使这个eval("l." + "append")
,因为在这种情况下ls
是附加的,并且eval
的最终输出是执行其各自计算的l.append
您可以参考这段简单的代码:
相关问题 更多 >
编程相关推荐