Notice
Recent Posts
Link
- Today
- Total
hye-log
[프로그래머스]키패드 누르기(Python) 본문
0. 문제 링크
https://school.programmers.co.kr/learn/courses/30/lessons/67256
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
1. 문제 설명
1) 왼쪽 열 키패드는 왼손으로
2) 오른쪽 열 키패드는 오른손으로
3) 가운데 열 키패드는 가까운 손으로 or 둘 다 같으면 어느 손잡이인지 기준으로
2. 입출력
# input
numbers = [1, 3, 4, 5, 8, 2, 1, 4, 5, 9, 5]
hand = 'right'
# output
answer = 'LRLLLRLLRRL'
3. 코드
1) 첫 번째 코드
def solution(numbers, hand):
# numbers : 눌러야 할 번호
# hand : 오른손잡이, 왼손잡이
answer = []
keypad = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '*', '0', '#']
left_pos = keypad.index('*') # 왼손 위치
right_pos = keypad.index('#') # 오른손 위치
for i in range(len(numbers)):
press_key = keypad.index(str(numbers[i])) # 키패드 인덱스
result = ''
if press_key % 3 == 0: # 왼쪽 열이면 왼손
result = 'left'
elif press_key % 3 == 2: # 오른쪽 열이면 오른손
result = 'right'
else: # 가운데 열이면 가까운 손으로
left_diff = abs(press_key // 3 - left_pos // 3) + abs(press_key % 3 - left_pos % 3)
right_diff = abs(press_key // 3 - right_pos // 3) + abs(press_key % 3 - right_pos % 3)
if left_diff < right_diff: # 왼손이 가까우면 왼손
result = 'left'
elif left_diff > right_diff: # 오른손이 가까우면 오른손
result = 'right'
else:
if hand == 'left': # 둘 다 가까우면 왼손잡이
result = 'left'
else: # 둘 다 가까우면 오른손잡이
result = 'right'
if result == 'left': # 왼손이면
left_pos = press_key # 손 위치를 왼손으로
answer.append('L')
else: # 오른손이면
right_pos = press_key # 손 위치를 오른손으로
answer.append('R')
return ''.join(answer)
실행 결과
4. 알게된 점
5. Github 링크
https://github.com/iihye/Algorithm/blob/main/Programmers/press_keypad.py
GitHub - iihye/Algorithm
Contribute to iihye/Algorithm development by creating an account on GitHub.
github.com
728x90
'CodingTest > Programmers' 카테고리의 다른 글
[프로그래머스]음양 더하기(Python) (0) | 2022.07.20 |
---|---|
[프로그래머스]없는 숫자 더하기(Python) (0) | 2022.07.19 |
[프로그래머스]숫자 문자열과 영단어(Python) (0) | 2022.07.12 |
[프로그래머스]신규 아이디 추천(Python) (0) | 2022.07.12 |
[프로그래머스]로또의 최고 순위와 최저 순위(Python) (0) | 2022.07.08 |
Comments