본 글은 프로그래머스 문제를 풀 때 공부한 내용을 정리했습니다.
이 문제는 유저의 리스트 중, 금지해야할 유저들을 뽑을 때의 경우의 수를 찾는 문제입니다.
여러 명의 유저들 중, n명의 유저를 뽑을 때 금지해야하는 경우를 생각하자, 유저들의 조합을 먼저 생각했습니다.
이 점을 주목해 permutations로 뽑아주었습니다.
그리고 금지해야할 경우인지 체크해주는 문자열을 re 정규표현식으로 구현했습니다. 이 방식은 다른 사람의 코드를 참고로 구현했습니다.
문제에서 주어진 문자열들은 * 가 있는데, re에서 이는 최소 1개 이상의 반복을 의미합니다. 이 때문에 . 로 replace 해줌으로써 re.match할때 문제가 없습니다.
정규표현식을 통해 정리된 문자열과 유저 리스트에서 뽑은 유저와의 비교 과정에서 match에서 찾아진게 있고, 길이가 같다면 문제에서 원하는 유저라고 판단했습니다.
def solution(user_id, banned_id): #banned_check = set(banned_id_raw) #banned_id = list(banned_check) check_lst = list() option_lst = list(permutations(user_id,len(banned_id))) for lst in option_lst: count = 0 for i in range(len(banned_id)): check = re.compile(f"^{banned_id[i].replace('*','.')}$") # ban해야하는 문자열을 정규표현식으로 변경시 *는 반복을 의미하므로 replace해준다. print(check) flag = check.match(lst[i]) if flag and len(banned_id[i]) == flag.end(): # if there is a match and the length is the same -> then true it is. count +=1 if count == len(banned_id): # if we get the number of id 's make as list and append temp_lst = sorted(list(map(str,lst))) check_lst.append(temp_lst) answer = set(map(tuple,check_lst)) # and then set this as tuple return len(answer)