Set .discard(), .remove() & .pop()

Sort by

recency

|

1087 Discussions

|

  • + 0 comments

    For Python3 Platform

    n = int(input())
    s = set(map(int, input().split()))
    N = int(input())
    
    for _ in range(N):
        cmd = input().split()
        
        if(cmd[0] == "pop"):
            try:
                s.pop()
            except KeyError:
                pass
        elif(cmd[0] == "remove"):
            try:
                s.remove(int(cmd[1]))
            except KeyError:
                pass
        elif(cmd[0] == "discard"):
            s.discard(int(cmd[1]))
    
    print(sum(s))
    
  • + 0 comments
    # Python 3 so it could be accepted!
    
    # Enter your code here. Read input from STDIN. Print output to STDOUT
    
    n = int(input())
    s = set(map(int, input().split()[:n]))
    N = int(input())
    
    for _ in range(N):
        command = input().split()    
        if command[0] == 'pop':
            try:
                s.pop()
            except KeyError:
                pass
        elif command[0] == 'remove':
            try:
                s.remove(int(command[1]))
            except KeyError:
                pass
        else:
            s.discard(int(command[1]))
            
    print(sum(s))
    
  • + 0 comments
    n = int(input())
    s = set(map(int, input().split()))
    d = {
        "remove": lambda s,ele:s.remove(ele),
        "discard":lambda s,ele:s.discard(ele),
        "pop":lambda s:s.pop()
    }
    N = int(input())
    for _ in range(N):
        lst = input().split()
        op = lst[0]
        if op =='pop':
            d[op](s)
        else:
            val = int(lst[1])
            d[op](s,val)
            
    print(sum(s))
    
  • + 0 comments

    n=int(input()) s=set(map(int,input().split())) N=int(input()) for _ in range (N): command=input().split() if command[0]=="pop": s.pop() elif command[0]=="discard": s.discard(int(command[1])) elif command[0]=="remove": if int(command[1]) in s: s.remove(int(command[1]))

    print (sum(s))

  • + 0 comments

    Code only can be run in python3. Will have wrong answer in Pypy3

    n=int(input()) s=set(map(int,input().split())) N=int(input()) for _ in range (N): command=input().split() if command[0]=="pop": s.pop() elif command[0]=="discard": s.discard(int(command[1])) elif command[0]=="remove": if int(command[1]) in s: s.remove(int(command[1]))

    print (sum(s))