일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
Tags
- Level2
- Stack
- mysql
- 완전탐색
- lv4
- collections
- CodingTest
- 프로그래머스
- programmers
- 파이썬
- itertools
- lambda
- python
- sql
- 연습문제
- BFS
- time complexity
- 조합
- 시간복잡도
- 코딩테스트
- Queue
- join
- 데이터분석
- counter
- import re
- level4
- coding
- 코테
- coding test
- 코딩
- Today
- Total
ror_coding
[Programmers] [1차] 다트 게임 - 17682 본문
728x90
dart = re.findall(r'\d+|[a-zA-Z][^\d\s]*',dartResult) 는 string에서 \d+ 숫자, [a-zA-Z][^\d\s]* 문자와 특수문자를 구별하여 list에 저장한다 ! 또한 compile을 이용한 코드도 존재한다 ! 매우 유용한 코드들!
Question
0~10의 정수와 문자 S, D, T, *, #로 구성된 문자열이 입력될 시 총점수를 반환하는 함수를 작성하라.
다트 게임은 총 3번의 기회로 구성된다.
각 기회마다 얻을 수 있는 점수는 0점에서 10점까지이다.
점수와 함께 Single(S), Double(D), Triple(T) 영역이 존재하고 각 영역 당첨 시 점수에서 1제곱, 2제곱, 3제곱 (점수1 , 점수2 , 점수3 )으로 계산된다.
옵션으로 스타상(*) , 아차상(#)이 존재하며 스타상(*) 당첨 시 해당 점수와 바로 전에 얻은 점수를 각 2배로 만든다.
아차상(#) 당첨 시 해당 점수는 마이너스된다.스타상(*)은 첫 번째 기회에서도 나올 수 있다. 이 경우 첫 번째 스타상(*)의 점수만 2배가 된다.
(예제 4번 참고)스타상(*)의 효과는 다른 스타상(*)의 효과와 중첩될 수 있다. 이 경우 중첩된 스타상(*) 점수는 4배가 된다.
(예제 4번 참고)스타상(*)의 효과는 아차상(#)의 효과와 중첩될 수 있다. 이 경우 중첩된 아차상(#)의 점수는 -2배가 된다.
(예제 5번 참고)Single(S), Double(D), Triple(T)은 점수마다 하나씩 존재한다.스타상(*), 아차상(#)은 점수마다 둘 중 하나만 존재할 수 있으며, 존재하지 않을 수도 있다.
Point
- import re -> re.findall() 로 숫자 또는 문자+특수문자 조합 찾음.
- Single / Double / Triple 연산을 수행한 후 특수 문자 존재시 추가 연산 진행.
Code 1 : my code
import re
def SDT(num, c):
if c == 'S' : return num
elif c == 'D' : return num ** 2
else : return num ** 3
def solution(dartResult):
answer = []
dart = re.findall(r'\d+|[a-zA-Z][^\d\s]*',dartResult) # 숫자 또는 문자+특수문자 조합 찾음
for idx, chars in zip(range(1,len(dart)+1,2),dart[1::2]):
answer.append(SDT(int(dart[idx-1]),chars[0])) # 숫자,(Single/Double/Triple 연산)
if len(chars) == 2 :
if chars[1] == '*':
answer[len(answer)-1] *= 2
if len(answer) != 1 : answer[len(answer)-2] *= 2
elif chars[1] == '#':
answer[len(answer)-1] *= (-1)
return sum(answer)
Code 2 : compile 이용
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)
# print(dart)
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]]
# print(dart)
answer = sum(dart)
return answer
![](https://t1.daumcdn.net/keditor/emoticon/friends1/large/014.gif)
now me
On my github
728x90
'Algorithm > Python' 카테고리의 다른 글
[Programmers] 둘만의 암호 - 155652 (0) | 2024.10.14 |
---|---|
[Programmers] 대충 만든 자판 - 160586 (0) | 2024.10.14 |
[Programmers] 옹알이 (2) - 133499 (0) | 2024.10.13 |
[Programmers] 실패율 - 42889 (1) | 2024.10.12 |
[Programmers] 소수 찾기 - 12921 (0) | 2024.10.12 |