Instagram
youtube
Facebook

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

Mradul Mishra
Table of Contents

The first line contains integer , the number of elements in the set . The second line contains space separated elements of set . All of the elements are non-negative integers, less than or equal to 9. The third line contains integer , the number of commands. The next lines contains either pop, remove and/or discard commands followed by their associated value.

The first line contains integer N, the number of elements in the set.
The second line contains N space-separated elements of set. All of the elements are non-negative integers, less than or equal to 9.
The third line contains integer, the number of commands.
The next N  lines contains either pop, remove and/or discard commands followed by their associated value.

 

n = int(input())
s = set(map(int, input().split()))
N = int(input())
for i in range(N):
    cmd = list(map(str, input().split()))
    if cmd[0] == "pop":
        s.pop()
    elif cmd[0] == "remove":
        try:
            s.remove(int(cmd[1]))
        except:
            continue
    elif cmd[0] == "discard":
        try:
            s.discard(int(cmd[1]))
        except:
            continue
print(sum(s))

 

Add a comment:

Comments:

k chakravarthi

nothing

Pandu

1u1b🍯😑

vineela

i wanna learn and this site is very helpul

Srinithi

I want to know about coding

Harsh Tripathi

good

VIDHYA SHREE S

NIL

Mukesh

Most Eassy way to solve this question: n = int(input()) s = set(map(int, input().split())) t=int(input()) for _ in range(t): comand=input().split() if comand[0]=="pop": s.pop() elif comand[0]=="remove": s.remove(int(comand[1])) else: s.discard(int(comand[1])) print(sum(s))

yoga

GOOD