728x90
반응형

비트연산자를 쓸 수 있느냐를 물어보는 문제이다. 처음에는 그냥 bin을 써서 풀었는데,

확실히 비트연산자 쓰는 게 훨씬 편한 것 같다. 

 

풀이 1

def binary(num, n):
    b = bin(num)[2:]
    return (n - len(b))*'0' + b

def str_sum(n, s1, s2):
    s = ''
    for i in range(n):
        s += '#' if s1[i] == '1' or s2[i] == '1' else ' '
    return s

def solution(n, arr1, arr2):
    ans = [0]*n
    for i in range(n):
        ans[i] = str_sum(n, binary(arr1[i], n), binary(arr2[i], n))
    return ans

 

풀이 2 

비트연산자와 replace를 사용하니 훨씬 쉽게 풀린다

def solution(n, arr1, arr2):
    ans = []
    for i in range(n):
        b = bin(arr1[i] | arr2[i])[2:]
        ans.append((n - len(b))*' ' + b.replace('1', '#').replace('0', ' '))
        
    return ans
728x90
반응형
728x90
반응형

문제에 맞는 자료구조를 생성하고 활용해야 하는 문제이다.

이 문제의 경우에는 Counter를 사용해서 쉽게 풀 수 있다.

주의해야 할 점이 스테이지에 도달한 사람이 없을 때인데 이를 따로 처리해주지 않으면 런타임 에러가 난다.

이거 때문에 조금 푸는데 시간이 걸렸다. 

 

풀이

1. 각 스테이지별 도달한 유저의 수를 담은 딕셔너리를 생성(Counter)

2. 각 스테이지별 실패율 계산

3. 실패율을 기준으로 내림차순 정렬한 리스트의 인덱스를 반환

from collections import Counter

def solution(N, stages):
    ans = []
    n = len(stages)
    counter = Counter(stages)
    for i in range(1, N+1):
        if n:
            ans.append(counter[i] / n)
            n -= counter[i]
        else:
            ans.append(0)
                
    return [i+1 for i in sorted(range(N), key=lambda x : ans[x], reverse=True)]
728x90
반응형
728x90
반응형

문제 상황에 맞는 적절한 자료구조를 생성하고 활용해야 되는 문제다.

요즘 카카오 초반 문제 특징인 것 같은데, 이 문제의 경우에는 2개의 Dictionary를 사용했다.

python의 defaultdict를 거의 처음 사용해봤는데 꽤 좋은 것 같다.

dict의 메서드인 setdefault도 사용해봤지만 defaultdict 쪽이 조금 더 편한 것 같다.

 

풀이

1. 유저별 신고한 id를 저장하는 report_user_dict, 유저별 신고당한 횟수를 저장하는 report_cnt_dict를 생성한다.

2. 위의 두 사전을 사용해 유저가 신고한 id가 k번 이상인지 확인하고 카운트해준다. 

from collections import defaultdict

def solution(id_list, report, k):
    report_user_dict = defaultdict(set)
    report_cnt_dict = defaultdict(int)
    ans = []
    
    for arg in set(report):
        id, reported_id = arg.split()
        report_user_dict[id].add(reported_id)
        report_cnt_dict[reported_id] += 1
        
    for id in id_list:
        cnt = 0
        for reported_id in report_user_dict[id]:
            if report_cnt_dict[reported_id] >= k:
                cnt += 1 
        ans.append(cnt)
    
    return ans
728x90
반응형
728x90
반응형

간단한 구현 문제이다. 문제에서 정해준 순서대로 입력 문자열을 처리해주면 된다.

 

첫 번째 풀이  

리스트 사용

def solution(new_id):
    # 1
    new_id = new_id.lower()
    
    # 2
    li = [c for c in new_id if c.isalnum() or c in "-_."]
    
    # 3
    i = 0
    while i < len(li)-1:
        if li[i] == li[i+1] == '.':
            li.pop(i)
        else:
            i += 1
    
    # 4
    if li and li[0] == '.':
        li.pop(0)
    if li and li[-1] == '.':
        li.pop()
    
    # 5
    if li == []:
        li.append('a')
    
    # 6
    if len(li) >= 16:
        li = li[:15]
        if li[-1] == '.':
            li.pop()
    
    # 7
    if len(li) <= 2:
        while len(li) < 3:
            li.append(li[-1])
    answer = ''.join(li)
    
    return answer

 

두 번째 풀이

리스트를 생성할 필요가 있을까 싶어서 문자열로도 풀어봤다.

def solution(new_id):
    ans = ""

    # 1
    new_id = new_id.lower()
    
    # 2
    for c in new_id: 
        if c.isalnum() or c in "-_.":
            ans += c
    
    # 3
    while ".." in ans:
        ans = ans.replace("..", '.')
    
    # 4
    if ans and ans[0] == '.':
        ans = ans[1:]
    if ans and ans[-1] == '.':
        ans = ans[:-1]
    
    # 5
    if ans == '':
        ans = 'a'
    
    # 6
    if len(ans) >= 16:
        ans = ans[:15]
        if ans[-1] == '.':
            ans = ans[:-1]
    
    # 7
    while len(ans) < 3:
        ans += ans[-1]
        
    return ans
728x90
반응형

+ Recent posts