Notice
Recent Posts
Recent Comments
Link
250x250
반응형
DecordRay
[프로그래머스] Level2 : [1차] 뉴스 클러스터링[Python] 본문
728x90
반응형
문제 : https://school.programmers.co.kr/learn/courses/30/lessons/17677
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
풀이 :
1. str1 문자열 길이만큼 반복하여 두 글자씩 끊은 문자가 알파벳일경우 소문자로 변환하여 str1_arr에 저장(str2도 동일)
2. 합집합 구하는 과정
- str1_arr과 str2_arr의 원소들을 삭제하거나 추가하는 과정이 필요하므로 deepcopy(깊은 복사) 시행
- str1_arr_copy[i]가 str2_arr_copy에도 있다면 union에 추가 후 두 원소를 각 리스트에서 삭제
- str1_arr_copy[i]가 str2_arr_copy에도 없다면 union에 추가 후 str1_arr_copy에서 str1_arr_copy[i]삭제
3. 교집합 구하는 과정
- str1_arr과 str2_arr의 원소들을 삭제하거나 추가하는 과정이 필요하므로 deepcopy(깊은 복사) 시행
- str1_arr_copy[i]가 str2_arr_copy에도 있다면 intersection에 추가 후 str1_arr_copy에서 str1_arr_copy[i]삭제
- 반복문이 끝난 후 str2_arr_copy 리스트의 길이가 0이 아니라면 나머지 str2_arr_copy의 원소들을 intersection에 추가
코드 :
import copy
def solution(str1, str2):
answer = 0
str1_arr = [] # str1을 두 글자씩 끊어서 저장할 리스트
str2_arr = [] # str2을 두 글자씩 끊어서 저장할 리스트
# 두 글자씩 끊은 단어가 영문자로만 이루어져 있을 경우 소문자로 변환하여 리스트에 저장
for i in range(1,len(str1)):
temp = str1[i-1]+str1[i]
if temp.isalpha():
str1_arr.append(temp.lower())
for i in range(1,len(str2)):
temp = str2[i-1]+str2[i]
if temp.isalpha():
str2_arr.append(temp.lower())
# 합집합 구하는 과정
union = []
str1_arr_copy = copy.deepcopy(str1_arr)
str2_arr_copy = copy.deepcopy(str2_arr)
for i in range(len(str1_arr_copy)-1,-1,-1):
if str1_arr_copy[i] in str2_arr_copy:
temp = str1_arr_copy[i]
union.append(temp)
str1_arr_copy.remove(temp)
str2_arr_copy.remove(temp)
else:
temp = str1_arr_copy[i]
union.append(str1_arr_copy[i])
str1_arr_copy.remove(temp)
if len(str2_arr_copy) != 0:
union.extend(str2_arr_copy)
# 교집합 구하는 과정
intersection = []
str1_arr_copy = copy.deepcopy(str1_arr)
str2_arr_copy = copy.deepcopy(str2_arr)
for i in range(len(str1_arr_copy)-1,-1,-1):
if str1_arr_copy[i] in str2_arr_copy:
temp = str1_arr_copy[i]
intersection.append(temp)
str2_arr_copy.remove(temp)
if len(intersection) == 0 and len(union) == 0: # 교집합과 합집합이 공집합일 경우
answer = 65536
else: # 교집합과 합집합이 공집합이 아닐 경우
answer = int((len(intersection) / len(union) * 65536))
return answer
728x90
반응형
'알고리즘 > 프로그래머스' 카테고리의 다른 글
[프로그래머스] Level2 : 귤 고르기[Python] (0) | 2023.01.16 |
---|---|
[프로그래머스] Level2 : 전화번호 목록[Python] (0) | 2023.01.13 |
[프로그래머스] Level2 : n^2 배열 자르기[Python] (0) | 2023.01.12 |
[프로그래머스] Level2 : 프린터[Python] (0) | 2023.01.11 |
[프로그래머스] Level2 : 튜플[Python] (0) | 2023.01.10 |