시간초과 코드
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()
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