๋กœ์ผ“๐Ÿพ
article thumbnail

 

 

ํŒŒ์ด์ฌ์—๋Š” ์ •๋ง ์œ ์šฉํ•œ ํ•จ์ˆ˜๊ฐ€ ๋งŽ์Šต๋‹ˆ๋‹ค. ๊ทธ ์ค‘ Counter ๋Š” ์ œ๊ฐ€ ์ƒ๊ฐํ•˜๊ธฐ์— ๊ฐ€์žฅ ์œ ์šฉํ•œ ํ•จ์ˆ˜ ์ค‘์— ํ•˜๋‚˜๋ผ๊ณ  ์ƒ๊ฐํ•ฉ๋‹ˆ๋‹ค. 

์ด๋ฒˆ ๊ธ€์—์„œ๋Š” Collections ๋ชจ๋“ˆ ์ค‘ ํ•˜๋‚˜์ธ Counter ํ•จ์ˆ˜์— ๋Œ€ํ•ด์„œ ์•Œ์•„๋ณด๊ณ  2019 ์นด์นด์˜ค ๊ฒจ์šธ ์ธํ„ด์‰ฝ ํŠœํ”Œ ์— ๋ฐ”๋กœ ์ ์šฉํ•ด๋ณด๊ฒ ์Šต๋‹ˆ๋‹ค.

 

๊ทธ๋Ÿผ ๋ ›์ธ ๋‘๋”์ฝ”๋“œ!

 

Collections ์˜ Counter()


Counter ๋Š” ๋ฆฌ์ŠคํŠธ๋‚˜ ๋ฌธ์ž์—ด์˜ ๊ฐฏ์ˆ˜๋ฅผ dict ํƒ€์ž…์œผ๋กœ ๋ฐ˜ํ™˜ํ•ด์ฃผ๋Š” ํ•จ์ˆ˜์ž…๋‹ˆ๋‹ค. 

๋ง๋กœ ๋ฐฑ๋ฒˆ ์„ค๋ช…ํ•˜๋Š” ๊ฒƒ๋ณด๋‹ค ํ•œ๋ฒˆ์˜ ์˜ˆ์ œ๊ฐ€ ๋ณด๋Š” ๊ฒƒ์ด ๋” ์ข‹๊ฒ ์ฃ ?

 

Counter(["I", "am", "Iron", "man", "!", "!"])
# Counter({'!': 2, 'I': 1, 'am': 1, 'Iron': 1, 'man': 1})

Counter(["I", "am", "Iron", "man", "!", "!"])["!"]
# 2

Counter("I am Iron man !!")
# Counter({' ': 4, 'I': 2, 'a': 2, 'm': 2, 'n': 2, '!': 2, 'r': 1, 'o': 1})

 

most_common() ์„ ์ด์šฉํ•ด์„œ ๊ฐ€์žฅ ๊ฐฏ์ˆ˜๊ฐ€ ๋งŽ์€ ๊ฒƒ๋“ค์„ ๋‚ด๋ฆผ์ฐจ์ˆœ์œผ๋กœ ๋ฐ›์„ ์ˆ˜๋„ ์žˆ์Šต๋‹ˆ๋‹ค.

Counter("I am Iron man !!").most_common(1)
# [(' ', 4)]

Counter("I am Iron man !!").most_common(3)
# [(' ', 4), ('I', 2), ('a', 2)]

 

์ด๊ฒŒ ๋‹ค์ž…๋‹ˆ๋‹ค. ์•„์ฃผ ์‰ฝ์ฃ ? ๊ทธ๋Ÿผ ๋ฌธ์ œ์— ์ ์šฉํ•ด๋ณด์ฃ .

 

๋ฌธ์ œํ’€์ด


๋ฌธ์ œ๋Š” 2019 ์นด์นด์˜ค ๊ฒจ์šธ ์ธํ„ด์‰ฝ ํŠœํ”Œ ์ž…๋‹ˆ๋‹ค.

๋ฌธ์ œ์— ๋Œ€ํ•œ ์„ค๋ช…์€ ์ƒ๋žตํ•ฉ๋‹ˆ๋‹ค.

 

from collections import Counter
import re

def solution(s):
    nums = re.findall("\d+", s)
    return [int(x[0]) for x in sorted(Counter(nums).items(), key=lambda x: x[1], reverse=True)]

re ๋ชจ๋“ˆ์„ ์ด์šฉํ•ด์„œ ์ˆซ์ž๋“ค๋งŒ ์ถ”์ถœํ•œ ํ›„, Counter ํ•จ์ˆ˜๋ฅผ ํ†ตํ•ด ๊ฐ ๋ฌธ์ž์— ๋Œ€ํ•œ ๊ฐฏ์ˆ˜๋ฅผ dict ํƒ€์ž…์œผ๋กœ ๋ฐ›์Šต๋‹ˆ๋‹ค.

์ดํ›„ sorted ํ•จ์ˆ˜๋ฅผ ์ด์šฉํ•ด์„œ ์ •๋ ฌํ•ด์ค๋‹ˆ๋‹ค.

 

Counter ํ•จ์ˆ˜๋ฅผ ์ด์šฉํ•˜๋ฉด ๋ฌธ์ž์—ด์ด ์ฃผ์–ด์กŒ์„ ๋•Œ ํ•˜๋‚˜ํ•˜๋‚˜ for ๋ฌธ ๋Œ๋ ค์„œ ๊ฐฏ์ˆ˜๋ฅผ ์…€ ํ•„์š”๊ฐ€ ์—†์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค. ํ•œ์ค„๋กœ ์•„์ฃผ ๊ฐ„๋‹จํ•˜๊ฒŒ ๋ฌธ์ž์—ด ๊ฐฏ์ˆ˜๋ฅผ ์…€ ์ˆ˜ ์žˆ์ฃ .

 

๊ทธ๋Ÿผ ์˜ค๋Š˜์€ ์—ฌ๊ธฐ๊นŒ์ง€!

profile on loading

Loading...