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

Sort by

recency

|

1045 Discussions

|

  • + 0 comments

    This is for discard, pop and remove method. In this method, I have used getattr techniques as it handles the missing attribute and also it returns the value of an attribute.

    n = int(input()) s = set(map(int, input().split())) N= int(input()) for i in range(N): output = input().split() if len(output)==1: getattr(s,output[0])() try: if len(output)==2: output1 = getattr(s,output[0]) output1(int(output[1])) except: pass

    print(sum(s))

  • + 0 comments

    I believe sets do maintain insertion order from Python 3.7 so using .pop() will remove the 9 which returns an error with .remove(9) straight afterwards. This challenge might be a bit outdated?

    n = int(input())
    s = set(map(int, input().split()))
    N = int(input())
    for _ in range(N):
        command = input()
        if command == "pop":
            s.pop()
            continue
        word, value = command.split()
        if word == "remove":
            s.remove(int(value))
        elif word == "discard":
            s.discard(int(value))
    print(sum(s))
    
  • + 2 comments

    The issue is with "pop", it should pop the samllest element from the set but instead it is removing the last element from the set. I just want to understand why it is happening? here is my code

    n = int(input())
    lst = set(map(int, input().split()))
    num = int(input())
    for i in range(num):
        st = input().strip()
        if ' ' in st:
            x, y = st.split()
            y = int(y)
            if y in lst:
                getattr(lst, x)(y)
        else:
            if lst:
                getattr(lst, st)()
    print(sum(lst))
    
  • + 0 comments

    n = int(input()) s = set(map(int, input().split())) N=int(input())

    while N>0: C=input()

    if C == "pop" :
        if s:
            s.pop()
    
    elif C.startswith("discard") or C.startswith("remove") :
        operation,num = C.split()
        num =int(num)
        if operation ==  "discard":
            s.discard(num)
        elif operation == "remove" and num in s:
            s.remove(num)
    N-=1        
    

    print(sum(s))

  • + 0 comments

    If your solution doesn't work on PyPy3, try using Python 3 and it works. The pop command doesn't remove the same elements in both PyPy3 and Python 3