박상길, 『파이썬 알고리즘 인터뷰』를 정리한 내용입니다.
https://leetcode.com/problems/most-common-word/
Most Common Word - LeetCode
Can you solve this real interview question? Most Common Word - Given a string paragraph and a string array of the banned words banned, return the most frequent word that is not banned. It is guaranteed there is at least one word that is not banned, and tha
leetcode.com
문장이 주어질 때, 금지된 단어를 제외한 가장 흔하게 등장하는 단어를 출력하라.
단, 대소문자는 구분하지 않으며 구두점(마침표, 쉼표)는 무시한다.
https://docs.python.org/3/library/re.html
re — Regular expression operations
Source code: Lib/re/ This module provides regular expression matching operations similar to those found in Perl. Both patterns and strings to be searched can be Unicode strings ( str) as well as 8-...
docs.python.org
정규표현식 [^\w]는 (a~z, A~Z, 0~9, _)에 속하지 않는 문자열의 집합이라는 뜻이다.
class Solution:
def mostCommonWord(self, paragraph: str, banned: [str]) -> str:
words = [word for word in re.sub(r'[^\w]', ' ', paragraph.lower()).split()
if word not in banned]
return Counter(words).most_common(1)[0][0]
소문자로 변환하고 알파벳만 추출하고 금지된 단어를 필터링하는걸 한줄로 끝내다니...
가장 빈도수가 높은 단어를 구하는걸 한줄로 끝내다니...
파이썬 지린다...
[프로그래머스] 161988. 연속 펄스 부분 수열의 합| DP | 파이썬, 소스코드, 정답 (1) | 2023.06.04 |
---|---|
[LeetCode] Longest Palindrome Substring | 투포인터 | 파이썬 알고리즘 인터뷰, 정답, 소스코드 (1) | 2023.06.03 |
[프로그래머스] 150365. 미로 탈출 명령어| 그리디, BFS | 파이썬, 소스코드, 정답 (0) | 2023.05.30 |
[프로그래머스] 150367. 표현 가능한 이진트리| 시뮬레이션, 구현 | 파이썬, 소스코드, 정답 (1) | 2023.05.26 |
[파이썬 알고리즘 인터뷰] 자기 자신을 제외한 배열의 곱 | 리스트, 선형 자료구조 (1) | 2023.05.24 |