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

Sort by

recency

|

1091 Discussions

|

  • + 0 comments
    n = int(input())
    s = set(map(int, input().split()))
    N = int(input())
    
    for _ in range(N):
        inp = list(input().split())
        if len(inp) == 2:
            getattr(s, inp[0])(int(inp[1]))
        else:
            getattr(s, inp[0])()
    
    print(sum(s))
    
  • + 0 comments

    I also wanted to use lamda but realized there was a problem I saw before which also required dynamic function call like this. Studied getattr()() workings and here is a much much simpler way

    N = int(input())
    
    for _ in range(N):
        COMMAND = input().split()
        if len(COMMAND) == 1:
            getattr(s, COMMAND[0])()
        else:
            getattr(s, COMMAND[0])(int(COMMAND[1]))
    print(sum(s))
    
  • + 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

    change your language to python3 from pypy3 for correct result

  • + 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))