๐What I thought
ํ์ด์ฌ์ in/not in ๊ฐ์ ์์ฃผ ์ข์ ํค์๋๊ฐ ์์ผ๋๊น ๊ทธ๊ฑฐ ์ฌ์ฉํ์
stones for๋ฌธ ๋๋ฉด์ jewels์ ์์ผ๋ฉด cnt++
๐ํ์ด
๐ํ ์ค ํ์ด
class Solution :
def numJewelsInStones (self, jewels: str , stones: str ) -> int :
return sum (s in jewels for s in stones)
์์ผ๋ฉด cnt ++ ์์ผ๋ฉด pass
์ด๋ ๊ฒ ํ๋ ค๊ณ ํ๋๋ฐ ์ด๊ฑฐ๋ณด๋ค ๋ ๊ฐ๊ฒฐํ๊ฒ ๊ฐ๋ฅํ์ โ sum()
sum()์ bool ํ์
์ ๋ฐ์ดํฐ์ ์ฐ๋ฉด True์ ๊ฐ์๋ฅผ return
๐Dictionary
class Solution :
def numJewelsInStones (self, jewels: str , stones: str ) -> int :
hs = dict ()
for stone in stones:
hs[stone] = hs.get(stone, 0 ) + 1
cnt = 0
for jewel in jewels:
if jewel in hs:
cnt += hs[jewel]
return cnt
{๋ ์ข
๋ฅ : ๋ ๊ฐ์}
defaultDict()์ด ์๋๋ฏ๋ก ์กด์ฌํ์ง ์๋ ํค์ ๋ํ ์ฒ๋ฆฌ๋ฅผ ํด์ฃผ์ด์ผ ํจ
๐Counter
from collections import Counter
class Solution :
def numJewelsInStones (self, jewels: str , stones: str ) -> int :
stone = Counter(stones)
cnt = 0
for j in jewels:
cnt += stone[j]
return cnt
stones์ ๊ฐ ๋ฌธ์๊ฐ ํ๋์ ๋์ด๋ฏ๋ก Counter๋ก ๊ฐ ๋ฌธ์์ ๊ฐ์ ์ฒดํฌ
Counter๋ ์กด์ฌํ๋์ง ์ฒดํฌ ํ์๋ ์์
( โต ์กด์ฌํ์ง ์๋ ํค์ ๋ํด์๋ 0์ return)
๐What I learned
ํ์ด์ฌ์ in/not in ๊ฐ์ ์์ฃผ ์ข์ ํค์๋๊ฐ ์์ผ๋๊น ๊ทธ๊ฑฐ ์ฌ์ฉํ์
Counter๋ ์กด์ฌํ์ง ์๋ ํค์ ๋ํด KeyError๊ฐ ์๋๋ผ 0์ return
sum() ์ bool ํ์
์ ๋ฐ์ดํฐ์ ์ฐ๋ฉด True์ ๊ฐ์๋ฅผ return
๐๊ด๋ จ ์ง์