HackerRank-Python

Prepare > Python > Sets > Set .symmetric_difference() Operation

stem_sw 2023. 7. 24. 20:43
 

Set .symmetric_difference() Operation | HackerRank

Making symmetric difference of sets.

www.hackerrank.com

 

문제


Task

Students of District College have subscriptions to English and French newspapers. Some students have subscribed to English only, some have subscribed to French only, and some have subscribed to both newspapers.

You are given two sets of student roll numbers. One set has subscribed to the English newspaper, and one set has subscribed to the French newspaper. Your task is to find the total number of students who have subscribed to either the English or the French newspaper but not both.

Input Format

The first line contains the number of students who have subscribed to the English newspaper.
The second line contains the space separated list of student roll numbers who have subscribed to the English newspaper.
The third line contains the number of students who have subscribed to the French newspaper.
The fourth line contains the space separated list of student roll numbers who have subscribed to the French newspaper.

Output Format

Output total number of students who have subscriptions to the English or the French newspaper but not both.

 

=> 미국이나 프랑스 신문 중 하나만 구독하는 학생 수를 구해라

 

 

코드


a = input()
b = set(input().split())
c = input()
d = set(input().split())

k = b.symmetric_difference(d)

print(len(k))

 

 

 

 

노트


symmetric_difference() 연산자

a.symmetric_difference(b) # (a합집합b) 차집합 (a교집합b)
b.symmetric_difference(a) # (a & b) - (a | b)
# 위 두 행은 결과가 같음

a^b # 아래와 결과 같음
b^a # 위와 결과 같음
  • 연산자 (^)로도 가능

 

 

>>> s = set("Hacker")
>>> print s.symmetric_difference("Rank")
set(['c', 'e', 'H', 'n', 'R', 'r'])

>>> print s.symmetric_difference(set(['R', 'a', 'n', 'k']))
set(['c', 'e', 'H', 'n', 'R', 'r'])

>>> print s.symmetric_difference(['R', 'a', 'n', 'k'])
set(['c', 'e', 'H', 'n', 'R', 'r'])

>>> print s.symmetric_difference(enumerate(['R', 'a', 'n', 'k']))
set(['a', 'c', 'e', 'H', (0, 'R'), 'r', (2, 'n'), 'k', (1, 'a'), (3, 'k')])

>>> print s.symmetric_difference({"Rank":1})
set(['a', 'c', 'e', 'H', 'k', 'Rank', 'r'])

>>> s ^ set("Rank")
set(['c', 'e', 'H', 'n', 'R', 'r'])
  • 문자열이나 리스트 자료형도 set으로 바꿔서 연산해버림