개발일지/삽질

프로그래머스- 조이스틱- 그리디-파이썬

Millennials 2022. 11. 1. 20:08

문제

처음 내 풀이

def solution(name):


  def upper(char):
      return ord(char) - ord('A')
  def down(char):
      return ord('Z') - ord(char) + 1
  up_down = [min(upper(i),down(i)) for i  in name]

  right = len(name) - 1
  count = sum(up_down) + right
  if 'A' not in name:
      return count

  else :
      left = 0
      left_count = 0
      for i in range(len(name)-1):

          next = i + 1
          while name[next] == 'A' and next < len(name):
              left_count += (left * 2) + 1
              break
          left += 1

      final = min(left_count+sum(up_down), count)
      return final

답 - 참고 https://velog.io/@jqdjhy/%ED%94%84%EB%A1%9C%EA%B7%B8%EB%9E%98%EB%A8%B8%EC%8A%A4-%ED%8C%8C%EC%9D%B4%EC%8D%AC-%EC%A1%B0%EC%9D%B4%EC%8A%A4%ED%8B%B1-Greedy

[[프로그래머스, 파이썬] 조이스틱, Greedy

[프로그래머스, 파이썬] 코딩테스트 고득점 Kit - Greedy, level 2 조이스틱

velog.io](https://velog.io/@jqdjhy/%ED%94%84%EB%A1%9C%EA%B7%B8%EB%9E%98%EB%A8%B8%EC%8A%A4-%ED%8C%8C%EC%9D%B4%EC%8D%AC-%EC%A1%B0%EC%9D%B4%EC%8A%A4%ED%8B%B1-Greedy)

def solution(name):


    def upper(char):
        return ord(char) - ord('A')
    def down(char):
        return ord('Z') - ord(char) + 1
    up_down = [min(upper(i),down(i)) for i  in name]

    right = len(name) - 1
    count = sum(up_down) + right
    if 'A' not in name:
        return count

    else :
        left = 0
        move = []
        for i in range(len(name)):

            next = i + 1
            while next < len(name) and name[next] == 'A':
                next += 1
            move.append( min([right, i * 2 + len(name) - next, i + 2 * (len(name) - next)]) )
        return sum(up_down)+min(move)
반응형