[๋ฌธ์ ]
paragraph์์ ๋์๋ฌธ์, ์ผํ ๊ตฌ๋์ ๋ฑ์ ๋ฌด์ํ๊ณ , banned ๋จ์ด์ ํฌํจ๋์ง ์์ ๋จ์ด ์ค ๊ฐ์ฅ ๋ง์ด ๋ฑ์ฅํ ๋จ์ด ๋ฐํ
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"
[ํ์ด]
1. ์ ๋ ฅ๊ฐ์ ๋ํ ์ ์ฒ๋ฆฌ (re)
2. ๋ฑ์ฅํ ๊ฐ์ ์ธ๊ธฐ (counter)
3. return
[์ค๋ช ]
re.sub๋ฅผ ํ์ฉํ ๋ฌธ์์ด ์นํํ๊ธฐ
re.sub('ํจํด', '๋ฐ๊ฟ๋ฌธ์์ด', '๋ฌธ์์ด', ๋ฐ๊ฟํ์)
์ ๊ทํํ์ ๋ฌธ๋ฒ์ ๋ฐ๋ผ ๋ค์ํ ํจํด์ ๊ตฌ์ํ ์ ์๋ค.
- ๋ ๋ฒ์๋ ๋ํ๋ [a-z] - ์์ด ์๋ฌธ์
^ ๋ not์ ํด๋น , [^1] ๋ '1'๋ฅผ ์ ์ธํ ๋ชจ๋ ๋ฌธ์์ ์ผ์น, [1^]๋ '1'ํน์ '^'์ ์ผ์นํ๋ค.
\w๋ ๋ชจ๋ ์์ซ์,
\d: ์ซ์([0-9]),
\D : ๋น ์ซ์ ๋ฌธ์([^0-9]),
. ์ “๋ชจ๋ ๋ฌธ์”์ ์ผ์น
\s: ๊ณต๋ฐฑ ๋ฌธ์,
์ด๋ฅผ ํผํฉํ์ฌ ์ฐ๋ ๊ฒ๋ ๊ฐ๋ฅํ๋ฐ, [\s,.] ๋ ๋ชจ๋ ๊ณต๋ฐฑ, ',' ๋๋ '.'์ ์ผ์นํ๋ ๋ฌธ์
\Aword: ๋ฌธ์์ด์ ์์๊ณผ 'word'๊ฐ ์ผ์นํฉ๋๋ค.
end\Z: ๋ฌธ์์ด์ ๋๊ณผ 'end'๊ฐ ์ผ์นํฉ๋๋ค.
๋ฐ๋ณต
* : ca*t๋ 'ct' (0๊ฐ์ 'a' ๋ฌธ์), 'cat' (1๊ฐ์ 'a'), 'caaat' (3๊ฐ์ 'a' ๋ฌธ์) ๋ฑ๊ณผ ์ผ์น
๋ฆฌ์คํธ ์ปดํ๋ฆฌํจ์
- ํ์ด์ฌ์์ ๊ฐ๊ฒฐํ๊ฒ ๋ฆฌ์คํธ๋ฅผ ์์ฑํ๋ ๋ฐฉ๋ฒ ์ค ํ๋
new_list = [expression for item in iterable if condition]
- expression: ๊ฐ ํญ๋ชฉ์ ๋ํ ๊ณ์ฐ์ ๋๋ ํํ์์ ๋๋ค.
- item: ๋ฐ๋ณต๋๋ ๊ฐ ์์์ ๋ํ ๋ณ์๋ช ์ ๋๋ค.
- iterable: ๋ฐ๋ณต ๊ฐ๋ฅํ ๊ฐ์ฒด(๋ฆฌ์คํธ, ํํ, ๋ฌธ์์ด ๋ฑ)์ ๋๋ค.
- condition (์ ํ ์ฌํญ): ์กฐ๊ฑด์์ผ๋ก, ํํฐ๋ง ์กฐ๊ฑด์ ๋ํ๋ ๋๋ค.
์ฌ๋ฌ ์ค ํ ์คํธ์์ ๊ฐ ์ค์ ๊ธธ์ด๋ฅผ ๊ตฌํ๊ณ ์ ํ ๋
text = """This is a
multiline
text."""
line_lengths = [len(line) for line in text.split('\n')]
print(line_lengths)
๋ฐ๋ผ์ ์ด๋ฅผ ์ด์ฉํด ๊ฐ ๋จ์ด ๋ฆฌ์คํธ ์์ฑ
['bob', 'a', 'ball', 'the', 'ball', 'flew', 'far', 'after', 'it', 'was']
collections ๋ชจ๋์ ํฌํจ๋ Counter ํด๋์ค๋ ํ์ด์ฌ์์ ๊ฐ๋จํ๊ฒ ์์์ ๊ฐ์๋ฅผ ์ธ๊ธฐ ์ํ ์ ์ฉํ ๋๊ตฌ์ ๋๋ค. Counter ๊ฐ์ฒด๋ ๋ฐ๋ณต ๊ฐ๋ฅํ(iterable) ๊ฐ์ฒด(๋ฆฌ์คํธ, ํํ ๋ฑ)์์ ๊ฐ ์์์ ๊ฐ์๋ฅผ ์ ๋๋ค.
from collections import Counter
my_list = [1, 2, 3, 1, 2, 3, 1, 2, 1, 1]
my_counter = Counter(my_list)
print(my_counter) # Counter({1: 5, 2: 3, 3: 2})
most_common([n]): ๊ฐ์ฅ ๋น๋ฒํ๊ฒ ๋ํ๋๋ ์์์ ๊ทธ ๊ฐ์๋ฅผ ์์๋๋ก ๋ฐํํฉ๋๋ค. n์ ์ ๊ณตํ๋ฉด ์์ n๊ฐ๋ง ๋ฐํํฉ๋๋ค.
print(my_counter.most_common(2)) # [(1, 5), (2, 3)]
[๋ต]