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

[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค / Python ํŒŒ์ด์ฌ] ๋‹คํŠธ ๊ฒŒ์ž„(2018 ์นด์นด์˜ค ์ฝ”๋”ฉํ…Œ์ŠคํŠธ 1์ฐจ)

meeeeejin 2021. 4. 9. 16:35

๋ฌธ์ œ ๋งํฌ: programmers.co.kr/learn/courses/30/lessons/17682

 

์ฝ”๋”ฉํ…Œ์ŠคํŠธ ์—ฐ์Šต - [1์ฐจ] ๋‹คํŠธ ๊ฒŒ์ž„

 

programmers.co.kr

 

 

๋ฌธ์ œ ์„ค๋ช…

result, prev, curr์— ๊ฐ๊ฐ ๋ˆ„์  ์ ์ˆ˜, ๋ฐ”๋กœ ์ง์ „ ์ ์ˆ˜, ํ˜„์žฌ ์ ์ˆ˜๋ฅผ ์ €์žฅํ–ˆ์Šต๋‹ˆ๋‹ค. 

 

์ž…๋ ฅ์œผ๋กœ ์ฃผ์–ด์ง„ ๋ฌธ์ž์—ด์˜ ๋ฌธ์ž๋ฅผ ํ•˜๋‚˜์”ฉ ๋Œ๋ฉด์„œ ๋‹ค์Œ์„ ๊ณ„์‚ฐํ•ฉ๋‹ˆ๋‹ค. 

  1. ๋ฌธ์ž๊ฐ€ ์ˆซ์ž(0~9)๋ผ๋ฉด
    1) result์— prev๋ฅผ ๋”ํ•œ๋‹ค. (prev๋Š” ์ด์ œ ๋ณด๋„ˆ์Šค๋‚˜ ์˜ต์…˜์ด ์ ์šฉ ์•ˆ๋˜๋ฏ€๋กœ)
    2) curr๊ฐ€ prev๊ฐ€ ๋œ๋‹ค. 
    3) ํ˜„์žฌ ๋ฌธ์ž๊ฐ€ curr๊ฐ€ ๋œ๋‹ค. 
  2. ๋ฌธ์ž๊ฐ€ ๋ณด๋„ˆ์Šค(S, D, T)๋ผ๋ฉด
    1) D์ผ ๊ฒฝ์šฐ curr์„ ์ œ๊ณฑํ•œ๋‹ค. 
    2) T์ผ ๊ฒฝ์šฐ curr์„ ์„ธ์ œ๊ณฑ ํ•œ๋‹ค. 
  3. ๋ฌธ์ž๊ฐ€ ์˜ต์…˜(*, #)์ด๋ผ๋ฉด
    1) *์ผ ๊ฒฝ์šฐ prev์™€ curr์— 2๋ฅผ ๊ณฑํ•ด ๋‘ ๋ฐฐ๋กœ ๋งŒ๋“ ๋‹ค. 
    2) #์ผ ๊ฒฝ์šฐ curr์— -1์„ ๊ณฑํ•ด ํ•ด๋‹น ์ ์ˆ˜๋ฅผ ๋งˆ์ด๋„ˆ์Šค๋กœ ๋งŒ๋“ ๋‹ค. 

๋งˆ์ง€๋ง‰์— (result+ prev + curr)๋ฅผ ๋ฐ˜ํ™˜ํ•จ์œผ๋กœ์จ (์ฒซ ๋ฒˆ์งธ ์ ์ˆ˜ + ๋‘ ๋ฒˆ์งธ ์ ์ˆ˜ + ์„ธ ๋ฒˆ์งธ ์ ์ˆ˜)๋ฅผ ๋ฐ˜ํ™˜ํ•ฉ๋‹ˆ๋‹ค. 

 

์ฃผ์˜ํ•  ์ ์€ 1๋ฒˆ ๊ณผ์ •์—์„œ 10์ ์— ๋Œ€ํ•œ ์˜ˆ์™ธ์ฒ˜๋ฆฌ๋ฅผ ํ•ด์•ผํ•œ๋‹ค๋Š” ๊ฒƒ์ž…๋‹ˆ๋‹ค. 

    ten = False

    for i in range(len(dartResult)):
        if dartResult[i].isdecimal():   # ์ ์ˆ˜: 0 ~ 10์‚ฌ์ด์˜ ์ •์ˆ˜
            if ten:
                ten = False
                continue
			# (์ค‘๋žต)
            if curr == 1 and dartResult[i + 1] == '0': # 10์  ์˜ˆ์™ธ์ฒ˜๋ฆฌ
                curr = 10
                ten = True

 

์œ„์™€ ๊ฐ™์ด ํ˜„์žฌ ๋ฌธ์ž๊ฐ€ 1์ด๊ณ  ๋‹ค์Œ ๋ฌธ์ž๊ฐ€ 0์ด๋ฉด 10์ ์ด๋ฏ€๋กœ curr์— 10์„ ์ €์žฅํ•˜๊ณ , ten์ด๋ผ๋Š” ์ผ์ข…์˜ ํ”Œ๋ž˜๊ทธ(flag) ๋ณ€์ˆ˜๋ฅผ True๋กœ ์„ค์ •ํ•ด์ค๋‹ˆ๋‹ค. 

๊ทธ ๋‹ค์Œ ๋ฐ˜๋ณต๋ฌธ์„ ์‹คํ–‰ํ•˜๋ฉด dartResult[i] == 0์ด์ง€๋งŒ ten์ด True๊ธฐ ๋•Œ๋ฌธ์— ๋’ค์˜ ๊ณผ์ •์€ ์ƒ๋žตํ•˜๊ณ  ๋ฐ˜๋ณต๋ฌธ์„ continueํ•˜๊ฒŒ ๋ฉ๋‹ˆ๋‹ค.  

 

 

 

์†Œ์Šค์ฝ”๋“œ
def solution(dartResult):
    # ๋ˆ„์  ์ ์ˆ˜, ์ด์ „ ์ ์ˆ˜, ํ˜„์žฌ ์ ์ˆ˜
    result, prev, curr = 0, 0, 0
    ten = False

    for i in range(len(dartResult)):
        if dartResult[i].isdecimal():   # ์ ์ˆ˜: 0 ~ 10์‚ฌ์ด์˜ ์ •์ˆ˜
            if ten:
                ten = False
                continue
            result += prev
            prev = curr
            curr = int(dartResult[i])
            if curr == 1 and dartResult[i + 1] == '0': # 10์  ์˜ˆ์™ธ์ฒ˜๋ฆฌ
                curr = 10
                ten = True
        elif dartResult[i].isalpha():   # ๋ณด๋„ˆ์Šค: S, D, T
            if dartResult[i] == 'D':
                curr = curr ** 2
            elif dartResult[i] == 'T':
                curr = curr ** 3
        else:                           # ์˜ต์…˜: *, #
            if dartResult[i] == '*':
                prev *= 2
                curr *= 2
            elif dartResult[i] == '#':
                curr *= -1

    return result + prev + curr

 

 

 

 

 

 

728x90