728x90
https://programmers.co.kr/learn/courses/30/lessons/17682
출처 : 프로그래머스
def solution(dartResult):
n = ''
point = []
for i in dartResult:
if i.isdigit(): # 숫자면 n에 담기
n += i
if i == 'S': # S면 1제곱
n = int(n) **1
point.append(n)
n = ''
elif i == 'D': # D면 2제곱
n = int(n) **2
point.append(n)
n = ''
elif i == 'T': # T면 3제곱
n = int(n) **3
point.append(n)
n = ''
elif i == '*': # *(스타상)일때
if len(point)>1:
point[-2] *=2
point[-1] *=2
else: # 첫 번째 기회일 때
point[-1] *=2
elif i == '#': # #(아차상)일때
point[-1] *=(-1)
return sum(point)
풀이 1
dartResult 배열을 돌면서 숫자는 따로 관리해주고,
점수 또한 직전의 점수를 활용해야 할 부분이 있어서 배열로 관리해줬다.
S, D, T 가 나오면 각각 조건에 맞게 1, 2, 3씩 제곱해준다.
스타 상일 때는 point 배열이 1개일 때,
즉, 이번에 추가된 점수가 첫 번째 기회일 때만 현재 추가한 점수에 *2를 해주고
point 배열이 2이상부터는 추가된 점수와 직전의 점수에 각각 2를 곱해서 더해준다.
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
풀이 2
다른 사람 풀이다..
정규식을 활용한 풀이이다.
이렇게 보니 정규식으로 풀라고 낸 문제같다^^..
'알고리즘 문제 풀이 > 프로그래머스' 카테고리의 다른 글
[프로그래머스] 오픈채팅방 python (0) | 2022.04.09 |
---|---|
[프로그래머스] 최솟값 만들기 python (0) | 2022.04.06 |
[프로그래머스] 소수 찾기 python (0) | 2022.04.05 |
[프로그래머스] [1차] 비밀지도 python (0) | 2022.04.05 |
[프로그래머스] 최대공약수와 최소공배수 python (0) | 2022.04.04 |