2023. 7. 19. 22:41ㆍHackerRank-Python
Symmetric Difference | HackerRank
Learn about sets as a data type.
www.hackerrank.com
문제
Given 2 sets of integers, M and N, print their symmetric difference in ascending order. The term symmetric difference indicates those values that exist in either M or N but do not exist in both.
=> M과 N을 줄건데, 그 길이만큼의 정수 집합이 주어질 것. 각 집합의 공통되지 않은 부분들을 줄바꿔 출력하라.
코드
a = input()
b = set(map(int, input().split()))
c = input()
d = set(map(int, input().split()))
diff_set = set()
diff_set.update(b.difference(d))
diff_set.update(d.difference(b))
diff_list = list(diff_set)
diff_sort_list = sorted(diff_list)
for i in diff_sort_list:
print(i)
노트
a = input()
b = set(map(int, input().split()))
c = input()
d = set(map(int, input().split()))
diff_set = set()
diff_set.update(b.difference(d)) b의 차집합
diff_set.update(d.difference(b)) d의 차집합
diff_list = list(diff_set)
diff_sort_list = sorted(diff_list) # 리스트를 정렬
k = '\n'.join(str(s) for s in diff_sort_list)
print(k)
- 리스트를 문자열로 join 이용
- 근데 str(s) for s in diff_sort_list 는 뭘까...?(comprehension 문법임)
set(집합) 자료형
무작위 순서, 중복 불가
생성
s1 = set('1233')
s2 = set([1, 2, 3])
s3 = {1, 2, 3}
print(s2 == s3)
OUTPUT
{'2', '1', '3'}
{1, 2, 3}
{1, 2, 3}
True
추가
s1.add((5, 4)) # (5, 4)가 하나의 원소로 들어감
s1.update('a') # a가 있으면 추가 안됨. 중복 불가
삭제
s1.discard() # s1에 타겟이 없으면 아무일도 없음
s1.remove() # s1에 타겟이 없다면 에러
집합연산
a.union(b) == b.union(a) # a 합집합 b
a.intersect(b) == b.intersect(a) # a 교집합 b
a.difference(b) # a - b, a 차집합 b
b.difference(a) # b -a, b 차집합 a
두 번째 시도
a = int(input())
English = set(map(int, input().split()))
b = int(input())
French = set(map(int, input().split()))
print(len(English ^ French))
참조
Python - 리스트를 문자열로 변환
List를 문자열로 변환하는 방법을 소개합니다. 반복문을 이용하여 리스트를 문자열로 변환하는 코드를 구현, `join()`을 이용하면 다음과 같이 리스트를 문자열로 변환할 수 있음, 또한, `map()`과 joi
codechacha.com
[python] 파이썬 sort 리스트 정렬 (오름차순, 내림차순)
안녕하세요. BlockDMask입니다. 오늘은 리스트 본체를 정렬하는 sort 함수에 대해서 이야기해볼까 합니다. 파이썬 sort 하면서 오름차순 혹은 내림차순으로 정렬하는 것도 설명드리겠습니다. 파이썬
blockdmask.tistory.com
[파이썬] 리스트 출력 : 한줄에 하나의 요소씩 출력하는 방법
파이썬에서 print()를 사용하여 리스트를 출력하게되는 경우 기본적으로 한줄에 모든 요소들이 표시된다. 각각의 요소들을 줄 단위로 나누어 출력하는 방법엔 어떤게 있을까? for 문 temp = [1, 2, 3, 4
earthteacher.tistory.com
[파이썬 중급] unpacking에 대해서 잘 알고 계시나요?(*, ** 사용법)
안녕하세요 혹시 여러분은 UNPACKING(언패킹)에 대해서 잘 이해하고 쓰시고 계신가요? 아래 문제를 풀어보시겠어요? l1 = [1,2,3] l2 = ['python'] l3 = [*l1,*l2] a, *b, (c, *d) = l3 print(a) print(b) print(c) print(d) a, b,
yeko90.tistory.com
'HackerRank-Python' 카테고리의 다른 글
Prepare > Python > Sets > Set .discard(), .remove() & .pop() (0) | 2023.07.21 |
---|---|
Prepare > Python > Sets > Set .add() (0) | 2023.07.21 |
Prepare > Python > Sets > Introduction to Sets (1) | 2023.07.17 |
Prepare > Python > Strings > Capitalize! (0) | 2023.07.15 |
Prepare > Python > Strings > Alphabet Rangoli (0) | 2023.07.14 |