반응형

어제 저녁에 1시간 반정도를 고민하고 해봤는데 풀리지 않았던 문제이다.

결국 다른 사람의 코드를 봤다.

이해한 것을 바탕으로 안보고 코딩을 해서 풀었다.

 

나중에는 내 힘으로 머리를 쥐어짜내서라도 풀어보고 싶다..ㅎㅎ

 

 

참고 URL:

https://school.programmers.co.kr/questions/56519

 


문제

 


문제 설명

# 우선순위 숫자가 더 높은 프로세스를 먼저 꺼낸다

# 우선순위중에 3이 몇개인지 세고, 3을 다 뺐다면 
# 2가 몇개인지 세고, 2를 다 빼는 순서로 해야될 것 같다.

# priorities : 현재 실행 대기 큐(Queue)에 있는 프로세스의 중요도가 순서대로 담긴 배열
# location : 몇 번째로 실행되는지 알고싶은 프로세스의 위치 (번호는 0부터 시작)

 

 

 


코드

- 통과한 코드

#참고 URL
#https://school.programmers.co.kr/questions/56519
# 위 코드를 보고 안보고 생각하면서 코딩해봤음

def solution(priorities, location):
    answer = 0

    loc_order = []
    for _ in range(len(priorities)):
        for idx, num in enumerate(priorities):
            if max(priorities) == num:
                loc_order.append(idx)
                priorities[idx] = 0
                
            if len(priorities) == len(loc_order):
                break
                
        if len(priorities) == len(loc_order):
                break

    answer = loc_order.index(location) + 1

    
    return answer

 

 

- 제출에서 런타임 에러나는 코드 (원래 시도하던 코드)

# 실패한 코드

def solution(priorities, location):
    answer = 0
    loc = -1
    
    cnt_dic = dict()
    desc_num = sorted(list(set(priorities)))[::-1]
    for num in desc_num:
        cnt_dic[num] = priorities.count(num)

    
    # 빠져나가는 순서
    loc_order = []
    
    for idx, cnt in cnt_dic.items():
        if cnt == 0:
            continue
        if cnt == 1:
            loc = priorities.index(idx)
            loc_order.append(loc)
        else:  
            try:
                if loc != -1:
                    # 개수가 여러개인 경우 원래 뽑힌 위치 뒤에서부터 찾음
                    priorities.index(idx, loc)
                    loc = priorities.index(idx, loc)
            
                elif loc == -1:
                    # loc가 -1이라면 처음부터 찾는다.
                    loc = priorities.index(idx)
                
                loc_order.append(loc)
                
            except:
                # 찾지 못하면 모든 곳에서 해당 값이 있는지 확인
                    loc = priorities.index(idx)

            for i in range(cnt): 
                while True:
                    if loc in loc_order:
                        before_loc = loc
                        if loc+1 == len(priorities):
                            loc = priorities.index(idx, 0)
                        else:
                            loc = priorities.index(idx, loc + 1)
                        if loc not in loc_order:
                            loc_order.append(loc)    

                        
                        break
                    else:
                        loc_order.append(loc)
                        break

            
    answer = loc_order.index(location) + 1

    
    
    return answer

 

 

 

 


 

반응형

'코테공부' 카테고리의 다른 글

[Python] 연습문제 : 멀리 뛰기  (0) 2023.10.25
[Python] 연습문제 : N개의 최소공배수  (0) 2023.10.24
[Python] 스택/큐 : 기능개발  (0) 2023.10.20
[Python] 해시 : 의상  (0) 2023.10.20
[Python] 정렬 : H-Index  (0) 2023.10.16
복사했습니다!