Better Code, Better Life

주식가격 - 프로그래머스 - 파이썬 풀이 본문

Coding Test/Programmers

주식가격 - 프로그래머스 - 파이썬 풀이

심재훈 2019. 8. 3. 17:00

문제 풀이

prices의 왼쪽 price 부터 반복적으로 가격이 떨어지지 않은 기간을 구합니다.

적절히 get_non_decreasing_days 함수만을 구현하면 됩니다.

 

deque 자료구조를 통해 첫 번째 원소를 추출해내는 작업을 수월하게 할 수 있습니다.

프린터 문제 해설 에서 deque 설명을 참조하세요!

 

클린 코드 작성법

  1. 함수의 이름으로 동사를 이용합니다.

    1. get_non_decreasing_days
  2. 변수명을 실제 문제와 대응되게 짓습니다.

    1. non_decreasing_days
  3. for 문에서의 임시 변수 또한 i, j 보다 반복 대상을 잘 나타낼 수 있는 이름을 짓습니다.

    1. other_price

 

해답 코드

from collections import deque

def get_non_decreasing_days(price, prices_deque):
    non_decreasing_days = 0
    for other_price in prices_deque:
        if price <= other_price:
            non_decreasing_days += 1
        else:
            non_decreasing_days += 1
            break
    return non_decreasing_days

def solution(prices):
    prices_deque = deque(prices)
    answer = []
    while prices_deque:
        price = prices_deque.popleft()
        non_decreasing_days = get_non_decreasing_days(price, prices_deque)
        answer.append(non_decreasing_days)
    return answer

도움이 됐다면 공감버튼을 눌러주세요! 질문이 있다면 댓글 달아주세요!

 

문제 링크

 

코딩테스트 연습 - 주식가격 | 프로그래머스

초 단위로 기록된 주식가격이 담긴 배열 prices가 매개변수로 주어질 때, 가격이 떨어지지 않은 기간은 몇 초인지를 return 하도록 solution 함수를 완성하세요. 제한사항 prices의 각 가격은 1 이상 10,000 이하인 자연수입니다. prices의 길이는 2 이상 100,000 이하입니다. 입출력 예 prices return [1, 2, 3, 2, 3] [4, 3, 1, 1, 0] 입출력 예 설명 1초 시점의 ₩1은 끝까지 가격이 떨어지지

programmers.co.kr

Comments