Prepare > Python > Sets > Set .discard(), .remove() & .pop()

2023. 7. 21. 22:45HackerRank-Python

 

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

Different ways to omit set elements.

www.hackerrank.com

 

문제


You have a non-empty set s, and you have to execute N commands given in N lines.

The commands will be pop, remove and discard.

 

=> 대충 input해주는 거 보고 그대로 실행하란 얘기

 

 

 

 

코드


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


for i in range(N):
    a = input().split(' ')
    if a[0] == 'pop':
        s.pop()
    elif a[0] == 'remove':
        s.remove(int(a[1]))
    elif a[0] == 'discard':
        s.discard(int(a[1]))
      
       
print(sum(s))

 

 

 

 

노트


set.sum()

s.pop() # s의 마지막 원소를 return하고, s에서 삭제함. s에 x가 없으면 에러
s.pop(i) # s의 i번째 원소를 return하고, s에서 삭제함
s.remove(x) # s에서 x를 삭제함, s에 x가 없으면 에러발생
s.discard(x) # s에서 x를 삭제함, s에 x가 없어도 문제 없음

 

자료형 파악 잘하자...