친구가 Python 에서 Dictionary 연습용 문제를 추천해줘서 풀어봤다.
Python은 포함 연산자( not in / in ) 를 제공하는게 평소 C++과 다르게 너무 효율적이라
아직 적응이 안된다..
어쨌든! 이 문제는 Dictionary로 비교하는 문제로 연습하기 딱 좋았다!
문제
[HackerRank] Hash Tables : Ransom Note
Harold is a kidnapper who wrote a ransom note, but now he is worried it will be traced back to him through his handwriting. He found a magazine and wants to know if he can cut out whole words from it and use them to create an untraceable replica of his ransom note. The words in his note are case-sensitive and he must use only whole words available in the magazine. He cannot use substrings or concatenation to create the words he needs.
Given the words in the magazine and the words in the ransom note, print Yes if he can replicate his ransom note exactly using whole words from the magazine; otherwise, print No.
For example, the note is "Attack at dawn". The magazine contains only "attack at dawn". The magazine has all the right words, but there's a case mismatch. The answer is No.
Function Description
Complete the checkMagazine function in the editor below. It must print Yes if the note can be formed using the magazine, or No.
checkMagazine has the following parameters:
- magazine: an array of strings, each a word in the magazine
- note: an array of strings, each a word in the ransom note
Input Format
The first line contains two space-separated integers, and , the numbers of words in the magazine and the note..
The second line contains m space-separated strings, each magazine [ i ].
The third line contains n space-separated strings, each note [ i ].
Constraints
- 1 <= m, n <= 30000
- .1 <= | magazine [ i ] |, | note [ i ] | <= 5
- Each word consists of English alphabetic letters (i.e., a to z and A to Z ).
Output Format
Print Yes if he can use the magazine to create an untraceable replica of his ransom note. Otherwise, print No.
Sample Input 0
6 4
give me one grand today night
give one grand today
Sample Output 0
Yes
Sample Input 1
6 5
two times three is not four
two times two is four
Sample Output 1
No
Explanation 1
'two' only occurs once in the magazine.
Sample Input 2
7 4
ive got a lovely bunch of coconuts
ive got some coconuts
Sample Output 2
No
Explanation 2
Harold's magazine is missing the word some.
풀이
- 먼저 magazine에 있는 단어리스트를 { 단어 : 빈도수 } 형태의 dictionary로 만들어준다.
- 두번째 note에 있는 단어리스트를 반복문으로 돌면서
앞에서 만든 dictionary의 key값에 같은 단어가 존재하면 해당 단어값을 키값으로 dictionary에 접근하여 해당 값에 -1을 해준다.
또한, 그 값이 0보다 작아질 경우 "No"를 return 하도록 한다.
- 없는 단어가 존재하면 반복문을 중단하고 "No"를 return 하도록 한다.
#!/bin/python3
import math
import os
import random
import re
import sys
def checkMagazine(magazine, note):
dic = {}
result = True
for i in range(len(magazine)):
if magazine[i] not in dic.keys():
dic[magazine[i]] = 1
else:
dic[magazine[i]] += 1
for i in range(len(note)):
if note[i] in dic.keys():
dic[note[i]] -= 1
if dic[note[i]] < 0:
result = False
print('No')
break
else:
result = False
print('No')
break
if result == True:
print('Yes')
if __name__ == '__main__':
first_multiple_input = input().rstrip().split()
m = int(first_multiple_input[0])
n = int(first_multiple_input[1])
magazine = input().rstrip().split()
note = input().rstrip().split()
checkMagazine(magazine, note)
결과

'Algorithm > Python' 카테고리의 다른 글
| [Python] ChatGPT API를 활용한 토이프로젝트 (0) | 2024.08.02 |
|---|---|
| (이코테) 이것이 취업을 위한 코딩 테스트다 with 파이썬 (0) | 2021.05.22 |
| [백준] 1316 - 그룹 단어 체커 (Python) (3) | 2021.05.20 |
| [백준] 10870 - 피보나치 수 5 (Python) (0) | 2021.05.20 |
| 알고리즘 관련 파이썬 주요 라이브러리 (2) | 2021.05.19 |
댓글