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

2023. 7. 24. 20:16HackerRank-Python

 

Set .intersection() Operation | HackerRank

Use the .intersection() operator to determine the number of same students in both sets.

www.hackerrank.com

 

문제


Task

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

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

 

Input Format

The first line contains 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.

 

=> 정수 n, 공백구분된 n개의 학생번호, 정수 b, 공백구분된 b개의 학생번호가 인풋

n은 미국신문 구독학생 수, b는 프랑스신문 구독학생 수

두 신문을 모두 구독하는 학생 수를 구하라

 

 

 

 

코드


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

its = b & d

print(len(its))

 

 

 

 

노트


intersect() 연산자

a.intersect(b) # a와 b의 교집합. 위와 결과 같음
b.intersect(a) # b와 a의 교집합. 위와 결과 같음

a & b # 위와 결과 같음
b & a # 위와 결과 같음
  • and를 나타내는 연산자(&)로도 사용가능

 

 

출처: hackerrank

 

 

두 번째 시도

a = int(input())
English = set(map(int, input().split()))

b = int(input())
French = set(map(int, input().split()))

print(len(English & French))