큐, 스택의 주식가격! 어려운 문제는 아닌데.. 문제 이해하는데 시간이 좀.. 걸렸다. 앞에서 풀었던 기능개발이랑 프린터보다 훨 쉬운거같다!! 근데 큐 스택 문젠데.. 나는 그냥 이중포문으로 풀었다. 효율성 테스트 통과하면 된건가?..ㅎㅎ
내 코드
def solution(prices):
answer = []
for i in range(len(prices)-1):
answer.append(0)
for j in range(i+1,len(prices)):
if prices[i] <= prices[j]:
answer[i]+=1
else:
answer[i]+=1
break
answer.append(0)
return answer
먼저 이중 포문을 사용하여 prices[i]와 prices[i]보다 뒤에 있는 원소들( prices[j])과 비교한다.
뒤에 있는 원소가 같거나 더 크다면 가격이 떨어지지 않은 것이기 때문에 answer을 더해준다.
만약 뒤에 있는 원소가 더 작으면 가격이 떨어진 것이기 떄문에 1을 더하고 더이상 answer을 계산할 필요가 없으니 break해준다. (여기서 문제를 잘못이해해서 헤맸다.. 가격이 떨어진 그 순간도 초에 포함!)
그리고 가장 마지막 원소의 answer을 0으로 지정해준다.
다른 사람 코드
def solution(prices):
answer = [0] * len(prices)
for i in range(len(prices)):
for j in range(i+1, len(prices)):
if prices[i] <= prices[j]:
answer[i] += 1
else:
answer[i] += 1
break
return answer
내꺼랑 비슷하다. 다른점이 2가지가 있는데 answer을 0으로 초기화를 시켜준것이 있고 i의 범위를 끝까지 정해준것이 있다. 나는 왜 끝까지 안돌리고 저렇게 풀었지?..
다른사람 코드 2
from collections import deque
def solution(prices):
answer = []
prices = deque(prices)
while prices:
c = prices.popleft()
count = 0
for i in prices:
if c > i:
count += 1
break
count += 1
answer.append(count)
return answer
이분은 큐로 풀었다! deque로 만들어서 제일 앞 원소를 pop하고 비교한다. 알고리즘은 나랑 똑같은거같다.
deque
양방향 큐이다. 앞, 뒤 양쪽 방향에서 원소를 추가, 제거할 수 있다.
from collections import deque
deq = deque()
deq.appendleft(0)
deq.append(0)
deq.popleft()
deq.pop()
- deque.append(item) : item을 데크의 오른쪽 끝에 삽입한다.
- deque.appendleft(item) : item을 데크의 왼쪽 끝에 삽입한다.
- deque.pop() : 데크의 오른쪽 끝 원소를 return 하고 삭제한다.
- deque.popleft() : 데크의 왼쪽 끝 원소를 return 하고 삭제한다.
- deque.extend(array) : 주어진 array를 순환하면서 데크의 오른쪽에 추가한다.
- deque.extentleft(array) : 주어진 array을 순환하면서 데크의 왼쪽에 추가한다.
- deque.remove(item) : item을 데크에서 찾아 삭제한다.
- deque.rotate(num) : 데크를 num 만큼 회전한다. (양수면 오른쪽, 음수면 왼쪽)
from collections import deque
deq = deque([1,2,3,4,5])
deq.rotate(1)
print(deq)
deq = deque([1,2,3,4,5])
deq.rotate(2)
print(deq)
deq = deque([1,2,3,4,5])
deq.rotate(-1)
print(deq)
deq = deque([1,2,3,4,5])
deq.rotate(-2)
print(deq)
######
deque([5, 1, 2, 3, 4])
deque([4, 5, 1, 2, 3])
deque([2, 3, 4, 5, 1])
deque([3, 4, 5, 1, 2])
rotate설명이다! 엄청 유용하게 쓰일꺼같다 ㅎㅎ
'코딩테스트 > Python' 카테고리의 다른 글
[프로그래머스] 콜라츠 추측 (0) | 2021.07.29 |
---|---|
[프로그래머스] 평균 구하기 (0) | 2021.07.29 |
[프로그래머스] 하샤드 수 (0) | 2021.07.28 |
[프로그래머스] 핸드폰 번호 가리기 (0) | 2021.07.28 |
[프로그래머스] x만큼 간격이 있는 n개의 숫자 (0) | 2021.07.28 |