하루살이 개발자

[프로그래머스] Level2 문제풀이 (Python) 본문

코딩테스트

[프로그래머스] Level2 문제풀이 (Python)

하루살이 2023. 3. 16. 16:37
def solution(number, k):
    answer = [] # Stack
    
    for num in number:
        while k > 0 and answer and answer[-1] < num:
            answer.pop()
            k -= 1
        answer.append(num)
        
    return ''.join(answer[:len(answer) - k])

# 귤고르기 - Level2

- Counter

import sys
from collections import Counter
def solution(k, tangerine):
    answer = 0
    c = Counter(tangerine) # 갯수별  
    
    li = []
    total = 0
    for i in list(c):
        li.append(c[i])
        total += int(c[i])
         
    li.sort(reverse = True) 
    sum = 0
    count = 0
     
    for i in li:
 
        sum += i
        count += 1
        if sum >= k:
            answer = count
            break 
        
    return answer

 

 

# 주차요금 계산

- math.ceil(): 올림

- math.floor(): 내림

- try~except

- del: index로 삭제  del arr[index] / remove: 값 삭제 arr.remove(삭제할값)

- stack.items()

- sorted(list(stack.items()), key=lambda x: x[0]) 오름차순 정렬

import math

# fees: [기본 시간(분), 기본 요금(원), 단위 시간(분), 단위 요금(원)]
def get_fee(minutes, fees):
    return fees[1] + math.ceil(max(0, (minutes - fees[0])) / fees[2]) * fees[3]

def solution(fees, records):
    parking = dict()
    stack = dict()
    
    for record in records:
        time, car, cmd = record.split()
        hour, minute = time.split(":")
        minutes = int(hour) * 60 + int(minute) # 시간 -> 분 환산

        if cmd == 'IN':
            parking[car] = minutes 
        elif cmd == 'OUT':
            try:
                stack[car] += minutes - parking[car]
            except:
                stack[car] = minutes - parking[car]
            del parking[car] # 출차 차량 삭제
            
    print(parking.items())
    # 출차 기록 없는 차 23:59 출차 처리
    for car, minute in parking.items():
        try:
            stack[car] += 23*60+59 - minute
        except:
            stack[car] = 23*60+59 - minute
        
    return [get_fee(time, fees) for car, time in sorted(list(stack.items()), key=lambda x: x[0])]

# 큰 수 만들기

def solution(number, k):
    answer = [] # Stack
    
    for num in number:
        while k > 0 and answer and answer[-1] < num:
            answer.pop()
            k -= 1
        answer.append(num)
        
    return ''.join(answer[:len(answer) - k])

 

# 연속 부분 수열 합의 개수

from collections import deque
def solution(elements): 
    a = []
    for i in range(1, len(elements)+1):
        deq = deque(maxlen=i)
        for j in elements*2: # 리스트 두번 연속 7 9 1 1 4 7 9 1 1 4 
            deq.append(j)
            a.append(sum(deq)) 
             
    return (len(set(a)))

 

# 전화번호 목록

zip, startswith 함수

def solution(phone_book):
    answer = True
    phone_book = sorted(phone_book)
    
    for i in range(len(phone_book)-1):
        n = len(phone_book[i])
        if phone_book[i] in phone_book[i+1][:n]:
            return False
        
    ''' 
    dic = {}
    for i in phone_book:
        dic[i] = 0

    
    for i in dic: 
        for j in range(len(i)):
            if i[:j] in dic:
                return False
    '''
    return answer

def solution2(phoneBook):
    phoneBook = sorted(phoneBook)
    print(phoneBook)
    for p1, p2 in zip(phoneBook, phoneBook[1:]):
        print(p1, p2) 
        if p2.startswith(p1):
            return False 
    return True

# 프린터

import queue

def solution(priorities, location):
    answer = 0
 
    q = []
    li = []
    for i in range(len(priorities)):
        q.append([priorities[i], i])  
     
    while q: 
        x, y = q.pop(0)  
        if len(q) > 0 and x < max(q)[0]: 
                q.append([x, y])
             
        else: 
            li.append(y)
 
     
    for i in range(len(li)):
        if li[i] == location:
            answer = i+1
              
                
    return answer

# 땅따먹기

def solution(land): 
    
    for j in range(1, len(land)):
        land[j][0] += max(land[j-1][1], land[j-1][2], land[j-1][3])
        land[j][1] += max(land[j-1][2], land[j-1][3], land[j-1][0])
        land[j][2] += max(land[j-1][3], land[j-1][0], land[j-1][1])
        land[j][3] += max(land[j-1][0], land[j-1][1], land[j-1][2])
        
    return max(land[-1])

# 뒤에 있는 큰 수 찾기

def solution(numbers):
    n = len(numbers)
    answer = [-1] * n
      
    st = []
    for i in range(n):
        while st and numbers[st[-1]] < numbers[i]:
            answer[st.pop()] = numbers[i]
        st.append(i)
        
        
    return answer

# 124 나라의 숫자

def solution(n):
    result = []
    while n:
        t = n % 3
        if not t:
            t = 3
            n -= 1
        result.append(str(t))
        n //= 3
    print(result[::-1])
    for i in range(len(result)):
        if result[i] == '3':
            result[i] = '4'
    return ''.join(result[::-1])