AttackOnNunu

Once more into the fray


  • 홈

  • About

  • 태그

  • 카테고리

  • 아카이브

  • 검색

(PYTHON) Day - 11 Sets(3)

작성일 2020-03-01 In LANGUAGE 🚀 , PYTHON , HACKERRANK 댓글:

Reference

  • 문제 출처 - HackerRank
  • 파이썬 연습 - Practice - Python

개인적인 생각과 상상으로 작성한 내용들이 포함되어 있습니다
문제를 풀고 Discussion Tab을 참고하며 코드 스타일을 개선하려고 노력하고자 합니다


HackerRank

HackerRank의 Python 연습문제들은 아래와 같은 카테고리로 분류 된다

Subdomain - Introduction - Basic Data Types - Strings - Sets - Math - Itertools - Collections - Date and Time - Errors and Exceptions - Classes - Built-Ins - Python Functionals - Regex and Parsing - XML - Closures and Decorators - Numpy - Debugging


Sets

Problem

  • Set Mutations
  • The Captain’s Room
  • Check Subset
  • Check Strict Superset

기본 개념

MUTATIONS
집합의 변환(mutation)은 update() 함수가 기본이고,
intersection_update(), difference_update(), symmetric_difference_update() 기능도 제공함
각 함수는 기호로도 표현 가능하다

  • update() : |=
  • intersection_update() : &=
  • difference_update() : -=
  • symmetric_difference_update() : ^=

대표로 update() 함수의 예제만 살펴보겠다


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

> > > A = set("Hacker")
> > > B = set("Rank")
> > > A |= B
> > > print(A)
> > > set(['a', 'c', 'e', 'H', 'k', 'n', 'r', 'R'])

Set Mutations


문제 : 집합 A가 있을 때, N번의 변환을 거쳐서 최종 집합 A를 구하는 문제
입력 : 집합 A의 크기; 집합 A의 원소들; 변환 횟수 N; (2*N번 반복)operation 이름과 집합 n의 원소 수;
출력 : 최종 집합 A 원소들의 합

  • INPUT
  • OUTPUT

16
1 2 3 4 5 6 7 8 9 10 11 12 13 14 24 52
4
intersection_update 10
2 3 5 6 8 9 1 4 7 11
update 2
55 66
symmetric_difference_update 5
22 7 35 62 58
difference_update 7
11 22 35 55 58 62 66

38

eval() 함수를 사용한 방법

if **name** == '**main**':
A = int(input())
set_A = set(input().split())
N = int(input())

for _ in range(N):
operation, n = input().split()
set_n = input().split()
eval('set_A.{}({})'.format(operation, set_n))

print(sum([int(i) for i in set_A]))

getattr() 함수를 사용한 방법, 입력 받을 때 tuple 형식으로 받는 것도 인상적

if **name** == '**main**':
(_, A) = (int(input()),set(map(int, input().split())))
B = int(input())
for _ in range(B):
(command, newSet) = (input().split()[0],set(map(int, input().split())))
getattr(A, command)(newSet)

print (sum(A))

The Captain’s Room


문제 : 호텔의 방문객으로 몇몇 그룹의 관광객들과 캡틴(captain) 한명이 있을 때, 캡틴이 누구인지 찾는 문제
입력 : 관광객 그룹의 크기 K; 각 관광객들의 방 번호;
출력 : 캡틴의 방 번호

  • INPUT
  • OUTPUT

5
1 2 3 6 5 4 4 2 5 3 6 1 6 5 3 2 4 1 2 5 1 4 3 6 8 4 3 1 5 6 2

8

collections 모듈에서 .Counter() 함수를 사용해봤다

import collections

if **name** == '**main**':
K = int(input())
room_no = [e for e in input().split()]
s = collections.Counter(room_no)

print(*[k for k, v in s.items() if v==1])

수학적으로 계산한 방법
예제의 경우 대충 (8+8+8+8)//4 요론 느낌? 짧아서 읽으면 이해가 된다

k,arr = int(input()),list(map(int, input().split()))
myset = set(arr)

print(((sum(myset)\*k)-(sum(arr)))//(k-1))

Check Subset


문제 : 집합 A, B가 주어졌을 때 A가 B의 부분집합인지 확인하는 문제
입력 : 테스트케이스 수 T; {(T번 반복) 집합A 원소 수; 집합A의 원소들; 집합B 원소 수; 집합B의 원소들;}
출력 : True/False로 출력

  • INPUT
  • OUTPUT

3
5
1 2 3 5 6
9
9 8 5 6 3 2 1 4 7
1
2
5
3 6 5 4 1
7
1 2 3 5 6 8 9
3
9 8 2

True
False
False

if **name** == '**main**':

for \_ in range(int(input())):
nA = input()
set_A = {n for n in input().split()}
nB = input()
set_B = {n for n in input().split()}

print(set_A.issubset(set_B))

Check Strict Superset


문제 : n개의 집합들이 집합 A의 진부분 집합인지 확인하는 문제
입력 : 집합 A의 원소들; 비교할 집합의 수 n; (n번 반복) 비교할 집합의 원소들;
출력 : True/False로 출력
예제 : {1 2 3 4 5}는 진부분 집합이 맞지만 {100 11 12}는 아니므로 답은 False

  • INPUT
  • OUTPUT

1 2 3 4 5 6 7 8 9 10 11 12 23 45 84 78
2
1 2 3 4 5
100 11 12

False

if **name** == '**main**':
set_A = {n for n in input().split()}
ans = True

for _ in range(int(input())):
other = {n for n in input().split()}
if not other.issubset(set_A):
ans = False

print(ans)
  • 2줄만에 끝내다니…
a = set(input().split())
print(all(a > set(input().split()) for \_ in range(int(input()))))


(PYTHON) Day - 10 Sets(2)

작성일 2020-02-29 In LANGUAGE 🚀 , PYTHON , HACKERRANK 댓글:

Reference

  • 문제 출처 - HackerRank
  • 파이썬 연습 - Practice - Python

개인적인 생각과 상상으로 작성한 내용들이 포함되어 있습니다
문제를 풀고 Discussion Tab을 참고하며 코드 스타일을 개선하려고 노력하고자 합니다


HackerRank

HackerRank의 Python 연습문제들은 아래와 같은 카테고리로 분류 된다

Subdomain - Introduction - Basic Data Types - Strings - Sets - Math - Itertools - Collections - Date and Time - Errors and Exceptions - Classes - Built-Ins - Python Functionals - Regex and Parsing - XML - Closures and Decorators - Numpy - Debugging


Sets

Problem

  • No Idea!
  • Set .add()
  • Set .discard(), .remove() & .pop()
  • Set .union() Operation
  • Set .intersection() Operation
  • Set .difference() Operation
  • Set .symmetric_difference() Operation

No Idea!


문제 : 비교를 위한 배열(N) 하나와 서로소 집합 A, B가 있을 때, N의 원소가 A에 있으면 happiness +1, B에 있으면 happiness -1
입력 : 원소 수 n, m을 입력; 차례로 N 배열의 n개 원소와 집합 A, B의 m개 원소를 입력
출력 : happiness의 값
예제 : N 배열 - (1, 5, 3) A 집합 - (3, 1) B 집합 - (5, 7)
A 집합으로 인해 happiness +2, B 집합으로 인해 happiness -1, 최종 happiness = 1

  • INPUT
  • OUTPUT

3 2
1 5 3
3 1
5 7

1

element in set_a 표현으로 집합안에 원소가 존재하는지 확인할 수 있음

if **name** == '**main**':
n, m = map(int, input().split())
array_n = input().split()
set_a = {e for e in input().split()}
set_b = {e for e in input().split()}

happiness = 0
for element in array_n:
if element in set_a:
happiness += 1
if element in set_b:
happiness -= 1

print(happiness)

굳이 int 형으로 변환하지 않아도 됨

n, m = input().split()

array_n = input().split()
A = set(input().split())
B = set(input().split())

print(sum([(i in A) - (i in B) for i in array_n]))

Set .add()


문제 : Rupal이 방문한 나라의 이름을 출력(중복 삭제)
입력 : 반복할 횟수 n을 입력; 나라 이름을 횟수만큼 반복해서 입력
출력 : 총 나라의 개수
예제 : 7번 다른 나라를 방문했는데 UK와 France는 중복됨; 즉 distinct country는 5가 됨

  • INPUT
  • OUTPUT

7
UK
China
USA
France
New Zealand
UK
France

5

element in set_a 표현으로 집합안에 원소가 존재하는지 확인할 수 있음

if **name** == '**main**':
n = int(input())
stamps = set([input() for _ in range(n)])

print(len(stamps))

Set .discard(), .remove() & .pop()


문제 : 비교를 위한 배열(N) 하나와 서로소 집합 A, B가 있을 때, N의 원소가 A에 있으면 happiness +1, B에 있으면 happiness -1
입력 : 원소 수 n을 입력; 집합 s의 원소들 입력(모두 양의 정수, 9보다 작거나 같음); 명령어 수 N을 입력; 명령어 입력;
출력 : 최종 집합 s의 원소들 합
예제 : N 배열 - (1, 5, 3) A 집합 - (3, 1) B 집합 - (5, 7)
A 집합으로 인해 happiness +2, B 집합으로 인해 happiness -1, 최종 happiness = 1

  • INPUT
  • OUTPUT

9
1 2 3 4 5 6 7 8 9
10
pop
remove 9
discard 9
discard 8
remove 7
pop
discard 6
remove 5
pop
discard 5

4

eval() 함수를 사용하면 쉽게 해결 가능

if **name** == '**main**':
n = int(input())
s = set(map(int, input().split()))

for i in range(int(input())):
eval('s.{0}({1})'.format(*input().split()+['']))

print(sum(s))

Set .union() Operation


입력 : 학생 수 n 입력; 영어 신문을 구독하는 학생 번호 입력; 학생 수 b 입력; 프랑스 신문을 구독하는 학생 번호 입력
출력 : 영어 신문, 프랑스 신문 둘 중 하나라도 구독하는 학생 수
예제 : 영어 신문 구독하는 학생 번호 - (1 2 3 4 5 6 7 8 9) 프랑스 신문 - (10 1 2 3 11 21 55 6 8)
하나라도 구독하는 학생 번호 - (1 2 3 4 5 6 7 8 9 10 11 21 55)

  • INPUT
  • OUTPUT

9
1 2 3 4 5 6 7 8 9
9
10 1 2 3 11 21 55 6 8

13

union() 함수를 사용해서 합집합을 구함

if **name** == '**main**':
n = int(input())
eng_news = set(input().split())
b = int(input())
fra_news = set(input().split())

print(len(eng_news.union(fra_news)))

Set .intersection() Operation


입력 : 이전 문제와 같음
출력 : 영어 신문, 프랑스 신문 둘 다 구독하는 학생 수
예제 : 둘 다 구독하는 학생 번호 - (1 2 3 6 8)

  • INPUT
  • OUTPUT

9
1 2 3 4 5 6 7 8 9
9
10 1 2 3 11 21 55 6 8

5

intersection() 함수를 사용해서 합집합을 구함

if **name** == '**main**':
n = int(input())
eng_news = set(input().split())
b = int(input())
fra_news = set(input().split())

print(len(eng_news.intersection(fra_news)))

Set .difference() Operation


입력 : 이전 문제와 같음
출력 : 영어 신문만 구독하는 학생 수
예제 : 영어 신문만 구독한 학생 번호 - (4 5 7 9)

  • INPUT
  • OUTPUT

9
1 2 3 4 5 6 7 8 9
9
10 1 2 3 11 21 55 6 8

4

difference() 함수를 사용안해도 - 해서 구할수도 있다

if **name** == '**main**':
n = int(input())
eng_news = set(input().split())
b = int(input())
fra_news = set(input().split())

print(len(eng_news.difference(fra_news)))
# print(len(eng_news - fra_news))

Set .symmetric_difference() Operation


입력 : 이전 문제와 같음
출력 : 영어 신문만 구독하거나 프랑스 신문만 구독한 학생 수
예제 : 둘 다 구독하는 학생 번호 - (4 5 7 9 10 11 21 55)

  • INPUT
  • OUTPUT

9
1 2 3 4 5 6 7 8 9
9
10 1 2 3 11 21 55 6 8

8

symmetric_difference() 함수를 사용

if **name** == '**main**':
n = int(input())
eng_news = set(input().split())
b = int(input())
fra_news = set(input().split())

print(len(eng_news.symmetric_difference(fra_news)))


(PYTHON) Day - 9 Sets(1)

작성일 2020-02-28 In LANGUAGE 🚀 , PYTHON , HACKERRANK 댓글:

Reference

  • 문제 출처 - HackerRank
  • 파이썬 연습 - Practice - Python

개인적인 생각과 상상으로 작성한 내용들이 포함되어 있습니다
문제를 풀고 Discussion Tab을 참고하며 코드 스타일을 개선하려고 노력하고자 합니다


HackerRank

HackerRank의 Python 연습문제들은 아래와 같은 카테고리로 분류 된다

Subdomain - Introduction - Basic Data Types - Strings - Sets - Math - Itertools - Collections - Date and Time - Errors and Exceptions - Classes - Built-Ins - Python Functionals - Regex and Parsing - XML - Closures and Decorators - Numpy - Debugging


Sets

Problem

  • Introduction to Sets
  • Symmetric Difference

기본 개념

  • set 자료형은 크게 2가지 특징을 가진다
    • 정렬되지 않음(unordered collection of elements)
    • 중복 데이터가 없음(without duplicate entries)
  • ‘membership testing’이나 ‘eliminating duplicate entries’ 등에 사용된다

CREATING SETS


> > myset = {1, 2} # 값을 바로 선언하는 방법
> > myset = set() # set 자료형 초기화
> > myset = set(['a', 'b']) # list 를 set 자료형으로 변환
> > myset
> > {'a', 'b'}

MODIFYING SETS
add() 함수를 사용하는 방법과 update() 함수를 사용하는 방법이 있음


> > myset.add('c')
> > myset
> > {'a', 'c', 'b'}
> > myset.add('a') # 'a' 데이터가 이미 있음으로 변화가 없음
> > myset.add((5, 4))
> > myset
> > {'a', 'c', 'b', (5, 4)}

> > myset.update([1, 2, 3, 4]) # update() 는 iterable한 객체에만 작동함
> > myset
> > {'a', 1, 'c', 'b', 4, 2, (5, 4), 3}
> > myset.update({1, 7, 8})
> > myset
> > {'a', 1, 'c', 'b', 4, 7, 8, 2, (5, 4), 3}
> > myset.update({1, 6}, [5, 13])
> > myset
> > {'a', 1, 'c', 'b', 4, 5, 6, 7, 8, 2, (5, 4), 13, 3}

REMOVING ITEMS
discard() 함수와 remove() 함수가 있으며 하나의 인자(argument)를 전달받아 집합에서 제거함
해당 데이터가 없으면 discard() 는 아무것도 안하지만 remove() 는 KeyError exception을 발생시킴


> > myset.discard(10)
> > myset
> > {'a', 1, 'c', 'b', 4, 5, 7, 8, 2, 12, (5, 4), 13, 11, 3}
> > myset.remove(13)
> > myset
> > {'a', 1, 'c', 'b', 4, 5, 7, 8, 2, 12, (5, 4), 11, 3}

pop() 함수는 임의의 값을 반환하고 삭제
clear() 함수는 집합에 있는 모든 값을 삭제


> > myset.pop()
> > myset
> > 1
> > myset.clear()
> > myset
> > set()

COMMON SET OPERATIONS
union(), intersection() 그리고 difference() 함수가 있음


> > a = {2, 4, 5, 9}
> > b = {2, 4, 11, 12}
> > a.union(b) # a와 b 집합의 합집합
> > {2, 4, 5, 9, 11, 12}
> > a.intersection(b) # a와 b 집합의 교집합
> > {2, 4}
> > a.difference(b) # a와 b 집합의 차집합
> > {9, 5}

Introduction to Sets


문제 : Ms. Gabriel Williams 의 온실에 있는 나무들의 평균키를 구하라
입력 : 총 나무의 수 N과 각 나무의 키를 입력 받는다
출력 : 나무들의 평균키

  • INPUT
  • OUTPUT

10
161 182 161 154 176 170 167 171 170 174

169.375

수행시간에 대한 최적화는 딱히 생각하지 않고 그냥 로직에 따라 구현

def average(array):
Sum_of_distinct_heights = sum(set(array))
Total_number_of_distict_heights = len(set(array))

return Sum_of_distinct_heights/Total_number_of_distict_heights

if **name** == '**main**':
n = int(input())
arr = list(map(int, input().split()))
result = average(arr)
print(result)

Symmetric Difference


문제 : 두 집합의 대칭차(symmetric difference)를 오름차순으로 출력해라
입력 : 원소 개수 M, M개의 원소들, 원소 개수 N, N개의 원소들 (4줄 입력)
출력 : 대칭차를 한줄씩 출력

  • INPUT
  • OUTPUT

4
2 4 5 9
4
2 4 11 12

5
9
11
12

대칭차를 구하는 함수 symmetric_difference() 를 사용


# Enter your code here. Read input from STDIN. Print output to STDOUT

if **name** == '**main**':
M = int(input())
set_m = {int(element) for element in input().split()}
N = int(input())
set_n = {int(element) for element in input().split()}

print(*sorted(set_m.symmetric_difference(set_n)), sep='\n')

사실 1, 3번째 줄의 입력은 무의미하다
두개의 집합을 한줄로 입력 받는 방법을 기억해두자

a,b = [set(input().split()) for \_ in range(4)][1::2]
print(\*sorted(a^b, key=int), sep='\n')


1…101112…33
NUNU

NUNU

개인적으로 공부하면서 정리한 내용들을 블로그에 남기고 있습니다.
99 포스트
18 카테고리
53 태그
RSS
Creative Commons
© 2021 NUNU
Powered by Hexo v3.9.0
|
Theme – NexT.Mist v7.2.0