๐ก 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)