알고리즘 테스트/프로그래머스 문제풀이 및 해설
<프로그래머스 문제풀이: [1차] 다트> Level 1 - 파이썬
개발린이
2020. 12. 3. 16:17
def solution(dartResult):
dart_list = list(dartResult)
before_score = []
string = ''
for i in dart_list:
if i.isnumeric():
string += i
elif not i.isnumeric():
if string == '':
before_score.append(i)
else:
before_score.append(string)
string = ''
before_score.append(i)
score = []
for i in range(len(before_score)):
if before_score[i] == 'S':
score.append(int(before_score[i-1]))
elif before_score[i] == 'D':
score.append(int((before_score[i-1]))**2)
elif before_score[i] == 'T':
score.append(int((before_score[i-1]))**3)
elif before_score[i] == '#':
score[-1] *= -1
elif before_score[i] == '*':
if len(score)> 1:
score[-2] = (score[-2])*2
score[-1] = (score[-1])*2
else:
score[-1] = (score[-1])*2
return sum(score)
처음에는 import re
를 통해 풀면 더 간단할 것이라는 것을 알고 이를 활용해 풀어보려 했으나, regular expression에 익숙하지는 않은 나머지 포기하고 다른 방식으로 풀기로 했다
- dartResult를 숫자와 다른 특수부호 / SDT로 나누기 위해 긴 코딩을 하여 before_score에 저장시켰다
- S, D, T * # 일때를 모두 정의하여 score 이라는 배열에 추가한다
- 마지막으로 문제의 요구에 알맞게 출력한다.
하지만 이렇게 푸는 것 말고도 앞서 말한 정규식을 이용한 더 편리한 풀이가 있었다:
다른사람의 풀이
프로그래머스에서 가장 많은 좋아요를 받은 풀이이다
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
너무나도 간결하고 편리하게 풀었다. 딕셔너리, 정규식, 배열에 대한 높은 이해도를 보이는 것을 볼 수 있다. 정규식에 대해 조금 더 공부하고 잘 활용할 수 있도록 해야겠다.