-
[??? 프로그래머스] 조이스틱 - 탐욕법Algorithm/1일 1코테 2021. 7. 25. 17:17반응형
https://programmers.co.kr/learn/courses/30/lessons/42860?language=python3
뭔소리인지 이해가 안됨!
def solution(name): alpha = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','G','Z'] start_name = ['A' for _ in range(len(name))] name = list(name) answer = 0 curr_joystick = 0 for s_word, word in zip(start_name, name): print(curr_joystick) if s_word == word: answer += 1 continue # 오른쪽 r_idx = curr_joystick r_distance = 0 for _ in range(len(alpha)): if word == alpha[r_idx]: break else: if r_idx == len(alpha)-1: r_idx = 0 r_idx += 1 r_distance += 1 # 왼쪽 l_idx = curr_joystick l_distance = 0 for _ in range(len(alpha)): if word == alpha[l_idx]: break else: if l_idx == 0: l_idx = len(alpha) l_idx -= 1 l_distance += 1 if l_distance > r_distance: answer += r_distance curr_joystick = r_distance else: answer += l_distance curr_joystick = l_distance print(answer)
def solution(name): alpha = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'] start_name = [min(alpha.index(v)-0, len(alpha)-alpha.index(v)) for v in name] answer = 0 pre = '' print(start_name) for v in start_name: l_distance = v r_distance = len(alpha)-v print(pre, l_distance, r_distance) if l_distance == 0 : answer += 1 pre = 'l' continue if r_distance == 0: answer += 1 pre = 'r' continue if l_distance > r_distance: answer += r_distance if pre == 'l': answer += 1 pre = 'r' pre = 'r' else: answer += l_distance if pre == 'r': answer += 1 pre = 'l' pre = 'l' print('a ',answer)
def solution(name): change = [min(ord(i) - ord("A"), ord("Z") - ord(i)+1) for i in name] idx, answer = 0, 0 while True: answer += change[idx] change[idx] = 0 if sum(change) == 0: break left, right = 1, 1 while change[idx - left] == 0: left += 1 while change[idx + right] == 0: right += 1 answer += left if left < right else right idx += -left if left < right else right return answer
반응형'Algorithm > 1일 1코테' 카테고리의 다른 글
[🥲 프로그래머스] 구명보트 - 탐욕법 (0) 2021.07.25 [🥲 프로그래머스] 큰 수 만들기 - 탐욕법 (0) 2021.07.25 [🥲 프로그래머스] 베스트앨범 - hash (0) 2021.07.24 [🥲 프로그래머스] 위장 - hash (0) 2021.07.23 [🥲 프로그래머스] 전화번호 목록 - hash (0) 2021.07.22