๊ธฐ๋ก๋ฐฉ

Lv.2 : ํŠœํ”Œ ๋ณธ๋ฌธ

CodingTest/Python

Lv.2 : ํŠœํ”Œ

Soom_1n 2022. 9. 12. 22:01

๐Ÿ‘‰ ๋ฌธ์ œ๋งํฌ

 

ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค

์ฝ”๋“œ ์ค‘์‹ฌ์˜ ๊ฐœ๋ฐœ์ž ์ฑ„์šฉ. ์Šคํƒ ๊ธฐ๋ฐ˜์˜ ํฌ์ง€์…˜ ๋งค์นญ. ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค์˜ ๊ฐœ๋ฐœ์ž ๋งž์ถคํ˜• ํ”„๋กœํ•„์„ ๋“ฑ๋กํ•˜๊ณ , ๋‚˜์™€ ๊ธฐ์ˆ  ๊ถํ•ฉ์ด ์ž˜ ๋งž๋Š” ๊ธฐ์—…๋“ค์„ ๋งค์นญ ๋ฐ›์œผ์„ธ์š”.

programmers.co.kr



๐Ÿ”ธ ๋ฌธ์ œ ๋ถ„์„ ๐Ÿ”ธ

  • ์›๋ณธ ํŠœํ”Œ์—์„œ ์ฒซ ์›์†Œ๋Š” n๋ฒˆ, ๋งˆ์ง€๋ง‰ ์›์†Œ๋Š” 1๋ฒˆ ํ˜ธ์ถœ๋˜๋ฏ€๋กœ ์ถœํ˜„ ๋นˆ๋„์ˆ˜๋กœ ๋‚ด๋ฆผ์ฐจ์ˆœ ์ •๋ ฌํ•œ๋‹ค.
  • ๋ฌธ์ž์—ด๋กœ ์ž…๋ ฅ๋˜๋ฏ€๋กœ ์ˆซ์ž๋ฅผ ๋ฝ‘์•„๋‚ด๋Š” ๊ณผ์ •์ด ํ•„์š”ํ•˜๋‹ค.

๐Ÿ”ธ ์ฝ”๋“œ ๐Ÿ”ธ

from collections import Counter

def solution(s):
    answer = []

    for i in '{},':
        s = s.replace(i," ")
    
    nums = [int(n) for n in s.split()]
    cnt = Counter(nums)

    answer = [n for n, _ in cnt.most_common()]
    return answer

๐Ÿ”ธ ์ฝ”๋“œ ํ•ด์„ ๐Ÿ”ธ

  • ์ค‘๊ด„ํ˜ธ์™€ ์‰ผํ‘œ๋ฅผ replace()๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ๋ชจ๋‘ ๊ณต๋ฐฑ์œผ๋กœ ๋ฐ”๊พธ๊ณ , split()์„ ์‚ฌ์šฉํ•ด ํ•œ ์ˆซ์ž์”ฉ ๋ฆฌ์ŠคํŠธ์— ๋‹ด๋Š”๋‹ค.
  • ๋‹ด์€ ๋ฆฌ์ŠคํŠธ ์•ˆ์—์„œ ๋นˆ๋„์ˆ˜๋ฅผ Conter์˜ most_common()์œผ๋กœ ์„ธ์„œ ๋ฆฌ์ŠคํŠธ๋กœ ๋งŒ๋“ค๊ณ  ๋ฐ˜ํ™˜ํ•œ๋‹ค.

๐Ÿ”ธ end ๐Ÿ”ธ

  • ๋ฌธ์ œ ํ’€์ด ํฌ์ธํŠธ๋ฅผ ๋จผ์ € ๋ณด๊ณ  ๋“ค์–ด๊ฐ€๊ฒŒ ๋˜์–ด์„œ ์–ด๋ ต๊ฒŒ ๋Š๊ปด์ง€์ง€ ์•Š์•˜๋‹ค. ๋‹ค์Œ๋ถ€ํ„ฐ๋Š” ๊ผญ ๋ธ”๋ผ์ธ๋“œ๋กœ ๋ฌธ์ œ๋ฅผ ์ ‘ํ•ด์•ผ๊ฒ ๋‹ค.
  • ๋ฌธ์ž์—ด์„ ํŒŒ์‹ฑํ•˜๊ณ , Counter()์˜ most_common()์„ ์‚ฌ์šฉํ•˜๋Š”๊ฒŒ ์ต์ˆ™ํ•˜์ง€ ์•Š์•„์„œ ์ƒˆ์‚ผ์Šค๋Ÿฝ๊ฒŒ ๋‹ค์‹œ ๋ณต์Šตํ•˜์˜€๋‹ค.
  • ๋ฌธ์ž์—ด ํŒŒ์‹ฑ์„ replace()์™€ split() ๋ง๊ณ ๋„ ์ •๊ทœํ‘œํ˜„์‹์„ ํ†ตํ•œ ํ’€์ด๋„ ์žˆ์—ˆ๋Š”๋ฐ ์ œ์ผ ๊น”๋”ํ•œ ๊ฒƒ ๊ฐ™๋‹ค.
from collections import Counter
from re import findall

def solution(s):
    return [int(n) for n, _ in Counter(findall('\d+', s)).most_common()]

1๋ฒˆ ํ’€์ด, 2๋ฒˆ ํ’€์ด ๊ฒฐ๊ณผ

  • ์‹ ๊ธฐํ•˜๊ฒŒ ์ •๊ทœํ‘œํ˜„์‹์ด ์†๋„๊ฐ€ ๋” ๋Š๋ฆฌ๊ฒŒ ๋‚˜์˜จ ๋ฌธ์ œ๋„ ์žˆ์—ˆ๋‹ค.
728x90