Notice
Recent Posts
Recent Comments
Link
DevKim
[Python] 카카오 기출 - 다트 게임 본문
728x90
[첫번째 문제 접근]
- 정수가 0~9가 아닌 10까지 주어진 점과, 옵션이 있을 수도 있고 없을 수도 있다는 조건을 보고, 꼼꼼하게 모든 상황을 고려하여 구현해야겠다고 생각했고, 문자열을 슬라이싱하는 과정 중에 이것 저것 조건을 모두 찾아서 구현했다. 정답이지만 반복되는 부분과 긴 코드를 줄이기 위해 다른 사람들의 풀이를 검토해봄
[두번째 문제 접근]
- 다른 분의 코드를 보니 dictionary와 정규표현식 re를 통해 15줄 안에 구현한 코드를 발견하였다
- 정규 표현식을 이용하여 다트 한번에 주어지는 점수,보너스,옵션을 나누고 조건에 따라 dic에 있는 보너스와 옵션을 제곱하고 곱해줌
[알고리즘]
- 구현
[첫번째 코드]
def solution(dartResult):
answer = 0
result=[]
ans=[]
#세개의 세트를 만듦
i=0
while i<len(dartResult):
if i==len(dartResult)-2:
result.append([ dartResult[i], dartResult[i+1] ])
break
else:
#숫자로 10이 들어가있을 때
if dartResult[i]=='1' and dartResult[i+1]=='0':
#마지막이고 옵션 없음
if i==len(dartResult)-3:
result.append([ dartResult[i]+dartResult[i+1], dartResult[i+2] ])
break
else:
if dartResult[i+3]=='*' or dartResult[i+3]=='#': #옵션이 존재하면
result.append( [dartResult[i]+dartResult[i+1], dartResult[i+2], dartResult[i+3] ])
i+=4
else:
result.append([ dartResult[i]+dartResult[i+1], dartResult[i+2] ])
i+=3
#0~9 사이의 숫자만 있음
else:
if dartResult[i+2]=='*' or dartResult[i+2]=='#': #옵션이 존재하면
result.append( [dartResult[i], dartResult[i+1], dartResult[i+2] ])
i+=3
else:
result.append([ dartResult[i], dartResult[i+1] ])
i+=2
if i>=len(dartResult):
break
for i in range(3):
if len(result[i])==3: #옵션이 존재함
a=int(result[i][0]) #숫자
b=result[i][1] #보너스
c=result[i][2] #옵션
if b=='S':
a=a**1
elif b=='D':
a=a**2
elif b=='T':
a=a**3
if c=='*':
if i==0: #첫번째 나온 별임
a=a*2
else:
a=a*2
ans[i-1]=ans[i-1]*2
elif c=='#':
if i==0:
a=a*(-1)
else:
a=a*(-1)
else: #옵션이 존재 안함
a=int(result[i][0]) #숫자
b=result[i][1] #보너스
if b=='S':
a=a**1
elif b=='D':
a=a**2
elif b=='T':
a=a**3
ans.append(a)
for i in ans:
answer+=i
return answer
[두번째 코드]
import re
def solution(dartResult):
bonus={'S':1,'D':2,'T':3}
option={'':1,'*':2,'#':-1}
p=re.compile('([0-9]+)([SDT])([*#]?)')
result=p.findall(dartResult)
for i in range(3):
if i>0 and result[i][2]=='*':
result[i-1]*=2
result[i]=int(result[i][0])**int(bonus[result[i][1]])*int(option[result[i][2]])
answer=sum(result)
return answer
728x90
'알고리즘 PS' 카테고리의 다른 글
[Python] SWEA - D3 - #1206 - 1일차 View (0) | 2021.02.05 |
---|---|
[Python] 카카오 기출 - 키패드 누르기 (0) | 2021.02.02 |
[Python] 카카오 기출 - 실패율 (0) | 2021.02.02 |
[Python] 카카오 기출 - 비밀지도 (0) | 2021.02.02 |
[Python] 2021 카카오 기출 - 신규 아이디 추천 (0) | 2021.02.02 |
Comments