2023. 7. 23. 21:56ㆍHackerRank-Python
Set .union() Operation | HackerRank
Use the .union() operator to determine the number of students.
www.hackerrank.com
문제
Input Format
The first line contains an integer, n, the number of students who have subscribed to the English newspaper.
The second line contains n space separated roll numbers of those students.
The third line contains b, the number of students who have subscribed to the French newspaper.
The fourth line contains b space separated roll numbers of those students.
Output Format
Output the total number of students who have at least one subscription.
=> 정수 n, 공백구분된 n개의 학생번호, 정수 b, 공백구분된 b개의 학생번호가 인풋
n은 미국신문 구독학생 수, b는 프랑스신문 구독학생 수
적어도 하나의 신문을 구독하는 학생수를 구해라
코드
a = input()
b = set(input().split())
c = input()
d = set(input().split())
union = b.union(d)
print(len(union))
노트
union() 연산자
a.union(b) # 합집합 연산, a에 b를 합집합
b.union(a) # 위와 같은 결과
a | b # 위와 같은 결과
b | a # 위와 같은 결과
- or을 나나태는 연산자 (|)로도 사용 가능
enumerate() 함수
인덱스와 원소를 함께 출력하고 싶을 때
i = 0
for letter in ['a', 'b', 'c']:
print(i, letter)
0 a
0 b
0 c
파라미터를 인덱스와 원소로 이루어진 튜플(tuple)로 만들어줌
for i in enumerate(['a', 'b', 'c']):
print(i)
(0, 'a')
(1, 'b')
(2, 'c')
튜플 unpacking(인자풀기)
for i, letter in enumerate['a', 'b', 'c']:
print(i, letter)
0 a
1 b
2 c
시작 인덱스는 start= 파라미터로 설정
for i, letter in enumerate(['a', 'b', 'c'], start=3):
print(i, letter)
3 a
4 b
5 c
참조
파이썬의 enumerate() 내장 함수로 for 루프 돌리기
Engineering Blog by Dale Seo
www.daleseo.com
'HackerRank-Python' 카테고리의 다른 글
Prepare > Python > Sets > Set .difference() Operation (0) | 2023.07.24 |
---|---|
Prepare > Python > Sets > Set .intersection() Operation (0) | 2023.07.24 |
Prepare > Python > Sets > Set .discard(), .remove() & .pop() (0) | 2023.07.21 |
Prepare > Python > Sets > Set .add() (0) | 2023.07.21 |
Prepare > Python > Sets > Symmetric Difference (0) | 2023.07.19 |