Prepare > Python > Sets > No Idea!

2023. 9. 16. 22:37HackerRank-Python

 

No Idea! | HackerRank

Compute your happiness.

www.hackerrank.com

 

문제


Input Format

The first line contains integers n and m separated by a space.
The second line contains n integers, the elements of the array.
The third and fourth lines contain m integers, A and B, respectively.

Output Format

Output a single integer, your total happiness.

 

=> 정수 n개로 이뤄진 배열(N)과 정수 m개를 가진 서로소 set A, B을 줄건데, 배열(N)의 요소 각각이 A에 속하면 행복지수 +1, B에 속하면 -1 해서 행복지수를 구하라.

배열(N)의 요소는 중복가능 A와 B 어디에도 속하지 않으면 아무일도 일어나지 않음

 

 

 

 

코드


n, m = map(int, input().split())
N = list(map(int,input().split()))
A = set(map(int, input().split()))
B = set(map(int, input().split()))

happiness = 0
for i in N:
    if i in A:
        happiness += 1
    elif i in B:
        happiness -= 1
    
print(happiness)

 

 

 

 

노트


intersection()의 파라미터는 set로만 쓰일 필요 없음

a = [1, 2, 3]
b = set(a)
c = [3, 3, 4, 5]

b.intersection(c)  # {3}
  • 이게 되네

 

 

another code

n, m = map(int, input().split())
N = list(map(int,input().split()))
A = set(map(int, input().split()))
B = set(map(int, input().split()))

print(
    sum((i in A) - (i in B) for i in N)
)
  • 불린값을 사칙연산에 적용하면 0과 1로 취급되는 점을 이용
n, m = map(int, input().split())
N = list(map(int,input().split()))
A = set(map(int, input().split()))
B = set(map(int, input().split()))

print([(i in A) for i in N])  # [True, False, True]
print([(i in B) for i in N])  # [False, True, False]

 

 

 

 

참조


 

Discussion on No Idea! Challenge

Compute your happiness.

www.hackerrank.com