from itertools import combinations
from collections import Counter

def solution(orders, course): 
    # 코스요리 재구성 - 최소 2가지 이상 단품메뉴 + 최소 2명 이상이 시킨 메뉴, 인기 메뉴 
    answer = []
    for k in course:
        tmp = []
        for menu in orders:
            menuList = combinations(sorted(menu), k) # k개씩 오름차순 조합 만들기
            tmp += menuList
        cnt = Counter(tmp) # 만들어진 조합 리스트들 중에서, 각 원소들의 중복 수를 구해준다.
        
        # cnt.values() 조합의 개수를 출력 조합이 없고, 중복 개수가 1인 경우 출력 X
        if len(cnt) != 0 and max(cnt.values()) != 1:
            for x in cnt:
                if cnt[x] == max(cnt.values()):
                    answer.append(''.join(x))
    answer.sort()
    return answer
from collections import defaultdict
def solution(record):
    # 닉네임 변경 방법 - 기존에 채팅방에 출력되어 있던 메시지의 닉네임도 모두 변경
    # 1. 채팅방을 나가고, 새로운 닉네임으로 들어온다.
    # 2. 채팅방에 입장한 상태에서, 닉네임을 변경한다.
    
    answer = []
    userDict = defaultdict(str)

    for x in range(len(record)):
        tmp = record[x].split(' ')
        opt = tmp[0]
        uid = tmp[1]
        if len(tmp) >2:
            nickname = tmp[2]
            userDict[uid] = nickname 
        if opt == 'Enter':
            answer.append(uid+'님이 들어왔습니다.')
        elif opt == 'Leave':
            answer.append(uid+'님이 나갔습니다.')
        elif opt == 'Change':
            # 이름 변경
            userDict[uid] = nickname
    
    for x in range(len(answer)):
        idx = answer[x].index('님')
        userList = answer[x][:idx]
        answer[x] = userDict[userList] + answer[x][idx:] 
    return answer
from collections import defaultdict
import math
def solution(fees, records): 
    # 주차요금 - 기본시간(분), 기본요금(원), 단위시간(분), 단위요금(원)  
    # 자동차입/출차내역 - 시간(시:분), 차량번호, 내역(입차or출차)
    # 차량 번호가 작은 자동차부터 청구 금액 출력
    answer = []
    timeDict = defaultdict(str)
    totalDict = defaultdict(int)
    
    # 차량 번호마다, 총 사용 시간을 구한다. - 출차내역이 없으면 23:59 출차
    for x in range(len(records)):
        tmp = records[x].split(' ')
        hour = tmp[0]
        carNum = tmp[1]
        opt = tmp[2]
        
        if opt == 'IN':
            timeDict[carNum] = hour
        else:
            resTime = 0
            inTime = timeDict[carNum]
            inHour = int(inTime[:2])
            inMinute = int(inTime[-2:])
            outHour = int(hour[:2])
            outMinute = int(hour[-2:])
            timeDict[carNum] = '' # 초기화
            
            # 출차 시간(분) 계산
            if outMinute < inMinute:
                resTime = (outHour - inHour - 1)*60
                resTime += (60 - inMinute) + outMinute
            else:
                resTime = (outHour - inHour)*60
                resTime += (outMinute - inMinute)
            # 차량 번호의 사용 시간 업데이트
            totalDict[carNum] = totalDict.get(carNum, 0) + resTime 

    # 출차 기록이 없는 차량 번호 23:59으로 계산
    for key, value in timeDict.items():
        if len(value) != 0:
            time = (59 - int(value[-2:])) + (23 - int(value[:2]))*60
            totalDict[key] = totalDict.get(key, 0) + time

    # 요금 계산
    for key, value in totalDict.items():
        if value <= fees[0]: # 시간이 넘지 않은 경우
            totalDict[key] = fees[1] # 기본 요금
        else:
            remain = fees[1] + math.ceil((value - fees[0]) / fees[2]) * fees[3]
            totalDict[key] = remain

    # 차량번호별 정렬
    sorted_dict = dict(sorted(totalDict.items()))

    for i in sorted_dict.values():
        answer.append(i)
    return answer
import math
def isPrime(num):
    if num == 1:
        return False
    for x in range(2, int(math.sqrt(num) + 1)):
        if num % x == 0:
            return False
    return True
def solution(n, k):
    answer = 0
    tmp = ''
    
    # k진법 계산
    while n!=0:
        tmp += str(n%k)
        n //=k
    tmp = tmp[::-1] # 거꾸로 뒤집기
    
    arr = tmp.split('0')
    
    for x in range(len(arr)):
        if len(arr[x]) != 0 and isPrime(int(arr[x])): 
            answer += 1
    return answer
from collections import Counter
def makeList(input):
    output = []
    for x in range(0, len(input)-1):
        if input[x].isalpha() and input[x+1].isalpha(): 
            tmp = input[x]+input[x+1]
            output.append(tmp)
    return output

def solution(str1, str2):
    answer = 0
    arr1 = makeList(str1.lower())
    arr2 = makeList(str2.lower())
            
    # 중복 개수
    cnt1 = Counter(arr1)
    cnt2 = Counter(arr2)
    
    intersection = list((cnt1&cnt2).elements())
    union = list((cnt1|cnt2).elements())
    
    if len(intersection)==0 and len(union) ==0:
        return 65536
    answer = int((len(intersection)/len(union))*65536)
    return answer
import re
def solution(s):
    answer = []
    arr = s.split(',{')
    arr.sort(key=len) # 길이 순으로 정렬
    
    for x in arr:
        # 숫자로 해당하는 항목들을 리스트로 변경
        numbers = re.findall('\d+', x)
        for k in numbers:
            if int(k) not in answer:
                answer.append(int(k))
    return answer

LRU(Least Recently Used Alogorithm) 알고리즘

  • 가장 오랜 시간동안 사용하지 않은 페이지를 교체하는 알고리즘
  • 캐시 교체 정책(Cache Replacement Policy) 중 하나 - 이외에 FIFO(First In First Out), LFU(Least Frequently Used)
  • Cache Hit : 참조하려고 하는 메모리가 캐시에 있는 경우
  • Cache Miss : 참조하려고 하는 메모리가 캐시에 없는 경우
def solution(cacheSize, cities): # 캐시크기, 도시이름 -> 총 실행시간 출력
    answer = 0
    # LRU : 가장 오랜 시간동안 사용하지 않은 페이지 교체 알고리즘
    # hit : 참조하려고 하는 메모리가 캐시에 있는 경우
    # miss : 참조하려는 메모리가 캐시에 없는 경우
    
    cache = []
    
    if cacheSize == 0:
        return len(cities)*5
    
    for x in range(len(cities)):
        current = cities[x].lower()
        if current in cache: # 캐시 안에 있는 경우
            answer += 1
            cache.remove(current)
            cache.append(current)
        else: # 캐시 안에 없는 경우
            if len(cache) == cacheSize:
                cache.pop(0)
            cache.append(current)
            answer += 5
    return answer

https://app.codility.com/programmers/lessons/15-caterpillar_method/abs_distinct/

 

AbsDistinct coding task - Learn to Code - Codility

Compute number of distinct absolute values of sorted array elements.

app.codility.com

 

 

  • 내림차순 배열 A이 주어질 때
  • 절대 값으로 고유한 값들의 개수 구하기
  • O(N) or O(N*log(N))

 

def solution(A):
    res = []
    for i in A:
        res.append(abs(i))
    res = list(set(res))
    return len(res)

+ Recent posts