programmers | Lv1. ๋‹คํŠธ ๊ฒŒ์ž„ [Python]

yeonkยท2022๋…„ 3์›” 14์ผ

algorithm

๋ชฉ๋ก ๋ณด๊ธฐ
66/88
post-thumbnail

๐Ÿ’ก Python 3






๐Ÿ”— ๋ฌธ์ œ

[1์ฐจ] ๋‹คํŠธ ๊ฒŒ์ž„ [Link]






๐Ÿ’ป ์ฝ”๋“œ

def solution(dR):
    dR = dR.replace('10', 'N')
    result = []
    for i, s in enumerate(dR):
        if s == 'N': s = '10'     
        if s.isdigit():
            k = int(s)
            if dR[i+1] == 'D': k **= 2
            elif dR[i+1] == 'T': k **= 3
            result.append(k)
            
        if i ==2 and s == '*':
            r1 = result.pop()*2
            result.append(r1)
        elif i != 2 and s == '*':
            r1 = result.pop()*2
            r2 = result.pop()*2
            result.append(r2)
            result.append(r1)
        elif s == '#':
            result.append(result.pop()*(-1))
    return sum(result)






๐Ÿ’ฅ ๋‹ค๋ฅธ ์‚ฌ๋žŒ ์ฝ”๋“œ

์ •๊ทœํ‘œํ˜„์‹ ํ™œ์šฉ.

import re


def solution(dartResult):
    bonus = {'S' : 1, 'D' : 2, 'T' : 3}
    option = {'' : 1, '*' : 2, '#' : -1}
    p = re.compile('(\d+)([SDT])([*#]?)')
    dart = p.findall(dartResult)
    for i in range(len(dart)):
        if dart[i][2] == '*' and i > 0:
            dart[i-1] *= 2
        dart[i] = int(dart[i][0]) ** bonus[dart[i][1]] * option[dart[i][2]]

    answer = sum(dart)
    return answer
  • \d+: ํ•˜๋‚˜ ์ด์ƒ ์—ฐ๊ฒฐ๋œ ์ˆซ์ž

    • \d: ์ˆซ์ž 1๊ธ€์ž
    • + : ํ•˜๋‚˜ ์ด์ƒ
  • findall(): ์ •๊ทœ์‹๊ณผ ๋งค์น˜๋˜๋Š” ๋ชจ๋“  ๋ฌธ์ž์—ด์„ ๋ฆฌ์ŠคํŠธํ˜•์‹์œผ๋กœ ๋ฆฌํ„ด

๊ธ€๋งŒ๋ด์„œ๋Š” ๋ฌด์Šจ ์†Œ๋ฆฐ์ง€ ์ž˜ ๋ชจ๋ฅด๊ฒ ์–ด์„œ print ์ฐ์–ด๋ดค๋‹ค.



dR = "1S2D*3T"
def solution(dartResult):
    import re
    bonus = {'S' : 1, 'D' : 2, 'T' : 3}
    option = {'' : 1, '*' : 2, '#' : -1}
    p = re.compile('(\d+)([SDT])([*#]?)')
    dart = p.findall(dartResult)
	print(dart)

# output
	[('1', 'S', ''), ('2', 'D', '*'), ('3', 'T', '')]






์ฐธ๊ณ  ์ž๋ฃŒ

[ํŒŒ์ด์ฌ] ์ •๊ทœํ‘œํ˜„์‹(regular expression)
์ •๊ทœํ‘œํ˜„์‹ #2
04 ๋ชจ๋“  ๋ฌธ์ž์—ด ํŒจํ„ด ์ฐพ๊ธฐ (findall)

profile
๋ธ”๋กœ๊ทธ ์ด์ „ํ•˜์˜€์Šต๋‹ˆ๋‹ค.

0๊ฐœ์˜ ๋Œ“๊ธ€