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

Sort by

recency

|

1075 Discussions

|

  • + 0 comments
    n = int(input())
    s = set(map(int, input().split()))
    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

    Why would this not work:

    import sys

    def solution(n, values, lines, N): for i in range(N): if lines[i][0] == "d": values.discard(int(lines[i][-1])) elif lines[i][0] == "r": values.remove(int(lines[i][-1])) else: values.pop()

    return values
    

    if name=="main": n = int(input()) values = set(map(int, input().split())) N = int(input())

    lines = []
    for _ in range(N):
        lines.append(input().strip())
    
    result = solution(n, values, lines, N)
    print(result)
    
  • + 0 comments

    This code works just fine..

    n = int(input()) S = set(map(int,input().split())) N = int(input()) arr = [] for i in range(N): command = list(input().split()) if command[0] == 'pop': S.discard(min(S)) else: S.discard(int(command[1])) print(sum(S))

  • + 1 comment

    This question and solution needs to be updated as it depends on pop() removing a specific element. However, by definition the pop() method is used to remove and return an arbitrary element from a set. So in my case my solution results in 6 instead of the expected 4.

  • + 0 comments

    Here is HackerRank Set .discard(), .remove() & .pop() in python solution - https://programmingoneonone.com/hackerrank-set-discard-remove-pop-solution-in-python.html