순위 검색

발자·2023년 6월 7일
0

programmers

목록 보기
24/34

시간초과 코드

def solution(info, query):
    test_list = [['cpp', 'java', 'python'], ['backend', 'frontend'], ['junior', 'senior'], ['chicken', 'pizza']]
    items = dict()
    answer = []
    for i in range(4):
        for j in range(len(test_list[i])):
            items[test_list[i][j]] = (j+1)*10**i
    
    test = dict()
    for i in info:
        tem_input = i.split()
        tem_info = 0
        for j in range(4):
            tem_info += items[tem_input[j]]
        if tem_info not in test.keys():
            test[tem_info] = [int(tem_input[-1])]
        else:
            test[tem_info].append(int(tem_input[-1]))
    
    for i in query:
        tem_input = [x for x in i.split() if x != 'and']
        tem_info = 0
        tem_point = 0
        for j in range(4):
            if tem_input[j] != '-':
                tem_info += items[tem_input[j]]
        tem_info = str(tem_info).zfill(4)
        for x in test.keys():
            tf = 1
            for y in range(4):
                if str(tem_info)[y] != '0':
                    if str(x)[y] != str(tem_info)[y]:
                        tf = 0
            if tf:
                for y in test[x]:
                    if y >= int(tem_input[-1]):
                        tem_point += 1
        answer.append(tem_point)
            
    return answer

정답 코드

from itertools import combinations
from bisect import bisect_left
def solution(information, queries):
    answer = []
    test = dict()
    # information : 개발언어, 경력구분, 소울푸드로, 점수
    for info in information:
        info = info.split()
        # 개발언어, 경력구분, 소울푸드
        key = info[:4]
        # 점수
        score = int(info[-1])
        for i in range(5):
            # '-' 넣을 위치 조합
            for comb in combinations('0123', i):
                tmp = key[:]
                for j in comb:
                    tmp[int(j)] = '-'
                tmp = "".join(tmp)
                # 딕셔너리에 넣기
                if tmp not in test.keys():
                    test[tmp] = [score]
                else:
                    test[tmp].append(score)
    
    # 점수 정렬
    for value in test.values():
        value.sort()

    # 문의
    for query in queries:
        query = query.replace("and ", "")
        query = query.split()
        # 개발언어, 경력구분, 소울푸드
        key = "".join(query[:4])
        # 점수
        score = int(query[-1])
        # 점수보다 높은 점수의 갯수
        cnt = 0
        # 딕셔너리에 존재하면
        if key in test.keys():
            value = test[key]
            idx = bisect_left(value, score)
            cnt = len(value) - idx
        answer.append(cnt)
                
    return answer

0개의 댓글