819. Most Common Word Python3

Yelim Kim·2021년 9월 13일
0
post-thumbnail

Problem

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 that the answer is unique.

The words in paragraph are case-insensitive and the answer should be returned in lowercase.

Example 1:

Input: paragraph = "Bob hit a ball, the hit BALL flew far after it was hit.", banned = ["hit"]
Output: "ball"
Explanation: 
"hit" occurs 3 times, but it is a banned word.
"ball" occurs twice (and no other word does), so it is the most frequent non-banned word in the paragraph. 
Note that words in the paragraph are not case sensitive,
that punctuation is ignored (even if adjacent to words, such as "ball,"), 
and that "hit" isn't the answer even though it occurs more because it is banned.

Example 2:

Input: paragraph = "a.", banned = []
Output: "a"

Constraints:

1 <= paragraph.length <= 1000
paragraph consists of English letters, space ' ', or one of the symbols: "!?',;.".
0 <= banned.length <= 100
1 <= banned[i].length <= 10
banned[i] consists of only lowercase English letters.

My code

class Solution:
    def mostCommonWord(self, paragraph: str, banned: List[str]) -> str:
        string = re.sub("\!|\'|\?|\,|\;|\.|\""," ",paragraph)
        list=string.lower().split()
        
        list = [elt for elt in list if elt not in banned]

        temp = [wrd for wrd in list]
        res = mode(temp)
        return res

Review

접근 방향

  1. 특수문자가 문제에 지정되어 있어서 걔네들만 제거
  2. .lower()를 맨 마지막에 출력하면서 사용하려고 했더니 그렇게 되면 앞에 중복에서 인식을 못해줘서 앞으로 이동
  3. string 에서는 abcd라는 한 단어를 인식하지 못해서 banned=['abc']이면 abcdabc를 잘라먹음 -> 리스트로 변경
  4. banned안에 있는 단어들 제거
  5. 중복 제일 높은 단어 출력

다른 의견

  1. banned안에 특수문자 넣기
  2. max -> 딕셔너리로 구하기
  3. banned단어 제거를 하고 빈도수 높은 친구 출력. (빈도수 높은 애를 뽑고 banned에 있는지 확인 후 다시 출력이 더 빨랐을까요?)
profile
뜬금없지만 세계여행이 꿈입니다.

1개의 댓글

comment-user-thumbnail
2021년 11월 26일

The motive of providing accounts of all ranges on our platform is to give customers what they demand and what they deserve.
csgo accounts for sale
buy high tier csgo accounts

답글 달기