Prepare > Python > Sets > Set .discard(), .remove() & .pop()
2023. 7. 21. 22:45ㆍHackerRank-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가 없어도 문제 없음
자료형 파악 잘하자...
'HackerRank-Python' 카테고리의 다른 글
Prepare > Python > Sets > Set .intersection() Operation (0) | 2023.07.24 |
---|---|
Prepare > Python > Sets > Set .union() Operation (0) | 2023.07.23 |
Prepare > Python > Sets > Set .add() (0) | 2023.07.21 |
Prepare > Python > Sets > Symmetric Difference (0) | 2023.07.19 |
Prepare > Python > Sets > Introduction to Sets (1) | 2023.07.17 |