PYTHON中SET的替代方法

2024-09-26 22:51:40 发布

您现在位置:Python中文网/ 问答频道 /正文

当我试图解决黑客等级的问题时,(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

,但该集合不支持重复。我需要一个替代品。即使你知道解决这个问题的任何其他简单方法,也要用完整的解释来重播


Tags: nameinforsortrulepopremovelist
2条回答

所以,看看这个问题和你的解决方案,它看起来可以缩短很多。 以下是我的解决方案:

n = int(input())
l = []
for i in range(n):
    s = input().split(" ")
    ls = s[0]
    num = s[1:]
    if ls != "print":
        ls += "("+ ",".join(num) +")"
        eval("l."+ls)
    else:
        print(l)

另外,我不使用HackerRank,所以我不知道它是否能在所有条件下运行,但它在基本情况下确实能运行

说明:

.join()用一个左括号“(”)连接ls,用逗号连接参数,然后连接一个右括号

eval解析传递给此方法的表达式并运行它。这里,它获取列表l,并添加需要执行的函数。 例如:

附加6: eval("l." + ls)将使这个eval("l." + "append"),因为在这种情况下ls是附加的,并且eval的最终输出是执行其各自计算的l.append

您可以参考这段简单的代码:

n=int(input("Enter the number of commands: "))
total_list=[]

for i in range(n):
    x=input("Enter a command: ").split()
    
    #==== .lower() converts it into lower case.

    if x[0].lower()=="append":                                      #=== Split gives a list, check if the first element in lower case is equal to the parameter
        total_list.append(x[1])                                     #== Add the second element to list.
        print(f"Appended {x[1]} to the list.")


    elif x[0].lower()=="print":                                     #=== Split gives a list, check if the first element in lower case is equal to the parameter
        print(total_list)


    elif x[0].lower()=="insert":                                    #=== Split gives a list, check if the first element in lower case is equal to the parameter
        try:
            total_list.insert(int(x[1]),x[2])                       #=== Insert takes 1: integer as the index and 2: the element
            print(f"Inserted {x[2]} at index {x[1]}.") 
        except IndexError:                                          #=== If something is missing
            print(f"Could not insert as no value was provided.")


    elif x[0].lower()=="remove":                                    #=== Split gives a list, check if the first element in lower case is equal to the parameter
        try:
            total_list.remove(x[1])                                 #=== Remove the second element
            print(f"Removed {x[1]} from the list.")
        except Exception:                                           #=== If element is absent
            print(f"Could not remove as the element is not present")


    elif x[0].lower()=="sort":                                      #=== Split gives a list, check if the first element in lower case is equal to the parameter
        try:
            total_list=[int(y) for y in total_list]                 #== Convert everything to integer. 
            total_list.sort()                                       #=== Sort the list
            total_list=[str(y) for y in total_list]                 #=== Convert everything to string
        except Exception:                                           #=== If exception occurs
            total_list.sort()                                       #=== Just sort the list
        print("List sorted successfully.")


    elif x[0].lower()=="pop":                                       #=== Split gives a list, check if the first element in lower case is equal to the parameter
        total_list.pop()                                            #=== Remove the last element
        print("Removed the last element from the list.")


    elif x[0].lower()=="reverse":                                   #=== Split gives a list, check if the first element in lower case is equal to the parameter
        total_list.reverse()                                        #=== Reverse the list
        print("List reversed successfully.")


    else:
        print(f"Invalid command provided: {x[0]}")

相关问题 更多 >

    热门问题