함께하는 데이터 분석

[Programmers] 프로그래머스 파이썬 lv2(업데이트 중) 본문

코딩 테스트/프로그래머스

[Programmers] 프로그래머스 파이썬 lv2(업데이트 중)

JEONGHEON 2023. 7. 26. 22:12

최댓값과 최솟값

def solution(s):
    answer = list(map(int,s.split()))
    return str(min(answer)) + ' ' + str(max(answer))

 

JadenCase 문자열 만들기

def solution(s):
    answer = list(map(str, s.split(' ')))
    for i in range(len(answer)) :
        answer[i] = answer[i].capitalize()
    return ' '.join(answer)

 

최솟값 만들기

def solution(A, B) :
    A.sort()
    B.sort(reverse = True)

    summ = 0
    for i in range(len(A)) :
        summ += A[i] * B[i]
    
    return summ

 

올바른 괄호

def solution(s):
    arr = []
    for i in s :
        arr.append(i)
        if arr[-2:] == ['(', ')'] :
            for _ in range(2) :
                arr.pop()
                
    if len(arr) == 0 :
        return True
    else :
        return False

 

이진 변환 반복하기

def solution(s) :
    n = 0
    cnt = 0

    while True :
        n += s.count('0')
        s = s.count('1')
        cnt += 1
        s = bin(s)[2:]
        if s == '1' :
            break
        
    return [cnt, n]

 

숫자의 표현

def solution(n) :
    cnt = 0

    for i in range(1, n + 1) :
        summ = 0
        for j in range(i, n + 1) :
            summ += j
            if summ == n :
                cnt += 1
            elif summ > n :
                break
            
    return cnt

 

다음 큰 숫자

def solution(n) :
    cnt = bin(n)[2:].count('1')
    a = n + 1

    while True :
        if bin(a)[2:].count('1') == cnt :
            return a
            break
        else :
            a += 1

 

피보나치 수

def solution(n) :
    a, b = 0, 1
    for _ in range(n) :
        a, b = b, a + b
        
    return a % 1234567

 

짝지어 제거하기

def solution(s) :

    arr = []
    for i in s :
        arr.append(i)
        if len(arr) > 1 :
            if arr[-1] == arr[-2] :
                for _ in range(2) :
                    arr.pop()
    
    if len(arr) == 0 :
        return 1
    else :
        return 0

 

카펫

import math

def solution(brown, yellow) :
    for i in range(1, int(math.sqrt(yellow)) + 1) :
        if yellow % i == 0 :
            if brown == 2 * (i + yellow // i) + 4 :
                return sorted([i + 2, yellow // i + 2], reverse = True)

 

영어 끝말잇기

def solution(n, words) :
    idx = 0
    for i in range(1, len(words)) :
        if words[i - 1][-1] != words[i][0] or words[i] in words[:i] :
            idx = i
            break
            
    if idx == 0 :
        return [0, 0]
    else :
        return [i % n + 1, i // n + 1]

 

구명보트

from collections import deque

def solution(people, limit) :
    people = deque(sorted(people))

    cnt = 0
    while True :
        if len(people) > 1 :
            if people[0] + people[-1] <= limit :
                cnt += 1
                people.popleft()
                people.pop()
            
            else :
                cnt += 1
                people.pop()
        else :
            break
        
    return cnt + len(people)

 

예상 대진표

def solution(N, A, B) :
    answer = 1
    while True :
        if abs(A - B) == 1 and min(A, B) % 2 != 0 :
            break
        else :
            answer += 1
            if A % 2 == 0 :
                A //= 2
            else :
                A = A // 2 + 1
        
            if B % 2 == 0 :
                B //= 2
            else :
                B = B // 2 + 1

    return answer

 

점프와 순간 이동

def solution(N) :
    answer = 1
    while N > 1 :
        if N % 2 == 0 :
            N //= 2
        else :
            N -= 1
            answer += 1
        
    return answer

 

N개의 최소공배수

from math import gcd

def solution(arr) :
    a = arr[0]
    
    for i in arr :
        a = a * i // gcd(a, i)
        
    return a

 

멀리 뛰기

def solution(n) :
    a, b = 1, 1
    for _ in range(n) :
        a, b = b, a + b
    
    return a % 1234567

 

귤 고르기

from collections import Counter

def solution(k, tangerine) :
    tan = sorted(Counter(tangerine).values(), reverse = True)

    summ = 0
    for i in range(len(tan)) :
        summ += tan[i]
        if summ >= k :
            break
        
    return i + 1

 

괄호 회전하기

def solution(s) :
    cnt = 0
    for i in range(len(s)) :
        arr = list(s[i:] + s[:i])
        answer = []
        for j in arr :
            answer.append(j)
            if answer[-2:] == ['(', ')'] or answer[-2:] == ['{', '}'] or answer[-2:] == ['[', ']'] :
                for _ in range(2) :
                    answer.pop()
        
            
        if len(answer) == 0 :
            cnt += 1
            
    return cnt

 

연속 부분 수열 합의 개수

def solution(elements) :
    arr = []
    elements2 = elements * 2
    for i in range(len(elements)) :
        for j in range(len(elements)) :
            arr.append(sum(elements2[j:i + j]))
        
    return len(set(arr))

 

H-Index

def solution(citations) :
    arr = []
    for i in range(len(citations) + 1) :
        cnt = 0
        for j in citations :
            if j >= i :
                cnt += 1
        arr.append([cnt, i])

    for i in arr :
        if i[0] == i[1] :
            return i[1]
            break
        elif i[0] < i[1] :
            return i[1] - 1
            break

 

n^2 배열 자르기

def solution(n, left, right) :
    arr = []
    for i in range(left, right + 1) :
        arr.append(max(i % n + 1, i // n + 1))
    
    return arr

 

행렬의 곱셈

def solution(arr1, arr2) :
    answer = []
    for i in range(len(arr1)) :
        arr = []
        for j in range(len(arr2[0])) :
            summ = 0
            for k in range(len(arr2)) :
                summ += arr1[i][k] * arr2[k][j]
            arr.append(summ)
        answer.append(arr)
    
    return answer

 

캐시

from collections import deque

def solution(cacheSize, cities) :
    arr = deque()
    time = 0
    for i in cities :
        if i.lower() not in arr :
            time += 5
            arr.append(i.lower())
        else :
            time += 1
            arr.append(i.lower())
            arr.remove(i.lower())
        if len(arr) > cacheSize :
            arr.popleft()
    
    return time

 

할인 행사

from collections import Counter

def solution(want, number, discount) :
    dic = {}
    for i in range(len(want)) :
        dic[want[i]] = number[i]

    count = 0
    for i in range(len(discount)) :
        if Counter(discount[i:10 + i]) == dic :
            count += 1
        
    return count

 

의상

def solution(clothes) :
    dic = {}
    for i in clothes :
        dic[i[1]] = dic.get(i[1], 0) + 1

    count = 1
    for i in dic.values() :
        count *= i + 1
    
    return count - 1

 

튜플

def solution(s) :
    s = s.replace('{', '')
    s = s.replace('}', '')

    dic = {}
    for i in s.split(',') :
        j = int(i)
        dic[j] = dic.get(j, 0) + 1

    answer = sorted(dic, key = lambda x : -dic[x])
    
    return answer

 

기능 개발

def solution(progresses, speeds) :
    arr = []
    for i in range(len(progresses)) :
        if (100 - progresses[i]) % speeds[i] == 0 :
            arr.append((100 - progresses[i]) // speeds[i])
        else :
            arr.append((100 - progresses[i]) // speeds[i] + 1)

    arr1 = []
    for i in arr :
        if len(arr1) == 0 :
            arr1.append(i)
        else :
            if arr1[-1] > i :
                arr1.append(arr1[-1])
            else :
                arr1.append(i)

    dic = {}
    for i in arr1 :
        dic[i] = dic.get(i, 0) + 1

    answer = []
    for i in dic.values() :
        answer.append(i)
    
    return answer

 

프로세스

from collections import deque

def solution(priorities, location) :

    arr = []
    for i in range(len(priorities)) :
        arr.append([priorities[i], i])
        
    arr = deque(arr)

    answer = []
    while True :
        maxx = max(arr)[0]
        a = arr.popleft()
        if a[0] == maxx :
            answer.append(a[1])
        else :
            arr.append(a)
        
        if len(arr) == 0 :
            break
        
    return answer.index(location) + 1

 

[1차] 뉴스 클러스터링

def slicee(s) :
    arr = []
    for i in range(len(s) - 1) :
        a = s[i:i + 2]
        if a.isalpha() :
            arr.append(a.lower())
            
    return arr

def solution(str1, str2) :
    set1 = slicee(str1)
    set2 = slicee(str2)
    answer = set(set1 + set2)

    inter = 0
    union = 0
    for i in answer :
        inter += min(set1.count(i), set2.count(i))
        union += max(set1.count(i), set2.count(i))
    
    if union == 0 :
        return 65536
    else :
        return int(inter / union * 65536)

 

피로도

from itertools import permutations

def solution(k, dungeons) :
    arr = list(permutations(dungeons, len(dungeons)))

    answer = []
    for i in arr :
        cnt = 0
        a = k
        for j in i :
            if j[0] <= a :
                cnt += 1
                a -= j[1]
        answer.append(cnt)
    
    return max(answer)

 

타겟 넘버

 

 

전화번호 목록

def solution(phone_book):
    phone_book.sort()
    
    for i in range(len(phone_book) - 1) :
        if phone_book[i] in phone_book[i + 1][:len(phone_book[i])] :
            return False
    return True

 

k진수에서 소수 개수 구하기

def solution(n, k):    
    def rev(n, k) :
        rev_base = ''
        
        while n > 0 :
            n, mod = divmod(n, k)
            rev_base += str(mod)
            
        return rev_base[::-1]
    
    def prime_number(n) :
        if n == 1 :
            return False
        
        for i in range(2, int(n ** 0.5) + 1) :
            if n % i == 0 : 
                return False
        return True
            
    arr = list(map(str, rev(n, k).split('0')))
    
    cnt = 0
    for i in arr :
        if i != '' :
            s = int(i)
            if prime_number(s) :
                cnt += 1
                    
    return cnt

 

[3차] 압축

def solution(msg) :
    alpha = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
    answer = []

    idx = 0
    while True :
        idx += 1
        if msg[:idx] not in alpha :
            alpha.append(msg[:idx])
            answer.append(alpha.index(msg[:idx - 1]) + 1)
            msg = msg[idx - 1:]
            idx = 0
        
        if idx == len(msg) :
            break

    answer.append(alpha.index(msg) + 1)
    
    return answer

 

[3차] n진수 게임

def solution(n, t, m, p) :
    def rev(n, k) :
        rev_base = ''
        if n == 0 :
            return '0'
        while n > 0 :
            n, mod = divmod(n, k)
            if mod == 10 :
                rev_base += 'A'
            elif mod == 11 :
                rev_base += 'B'
            elif mod == 12 :
                rev_base += 'C'
            elif mod == 13 :
                rev_base += 'D'
            elif mod == 14 :
                rev_base += 'E'
            elif mod == 15 :
                rev_base += 'F'
            else :
                rev_base += str(mod)
        
        return rev_base[:: -1]

    answer = ''
    for i in range(t * m) :
        answer += rev(i, n)
    
    
    result = ''
    for i in range(len(answer)) :
        if i % m == p - 1 :
            result += answer[i]
        
    return result[:t]

 

더 맵게

 

 

주차 요금 계산

import math

def solution(fees, records) :
    arr = []
    for i in records :
        arr.append(list(map(str, i.split())))

    for i in arr :
        i[0] = i[0].replace(':', '')
        i[0] = int(i[0][-2:]) + int(i[0][:2]) * 60

    number = []
    for i in arr :
        number.append(i[1])
    
    number = list(set(number))
    number.sort()

    answer = []
    for i in range(len(number)) :
        arr1 = []
        for j in arr :
            if number[i] == j[1] :
                arr1.append(j)
        answer.append(arr1)

    result = []
    for i in answer :
        summ = 0
        for j in range(len(i)) :
            if j % 2 == 0 :
                summ -= i[j][0]
            else :
                summ += i[j][0]
            
        result.append(summ)

    result1 = []
    for i in result :
        if i <= 0 :
            result1.append(i + 23 * 60 + 59)
        else :
            result1.append(i)

    array = []
    for i in result1 :
        if i <= fees[0] :
            array.append(fees[1])
        else :
            array.append(fees[1] + math.ceil((i - fees[0]) / fees[2]) * fees[3])
        
    return array

 

오픈채팅방

def solution(record) :
    arr = []
    for i in record :
        arr.append(list(map(str, i.split())))
    
    enterchange = []
    for i in arr :
        if i[0] == 'Enter' or i[0] == 'Change' :
            enterchange.append(i)
    
    dic = {}
    for i in enterchange :
        dic[i[1]] = i[2]

    enterleave = []
    for i in arr :
        if i[0] == 'Enter' or i[0] == 'Leave' :
            enterleave.append(i)

    result = []
    for i in enterleave :
        if i[0] == 'Enter' :
            result.append(f'{dic[i[1]]}님이 들어왔습니다.')
        else :
            result.append(f'{dic[i[1]]}님이 나갔습니다.')
        
    return result

 

주식가격

from collections import deque

def solution(prices) :
    prices = deque(prices)
    result = []
    while prices :
        a = prices.popleft()
        cnt = 0
        for i in prices :
            if i >= a :
                cnt += 1
            else :
                cnt += 1
                break
        result.append(cnt)
            
    return result

 

땅따먹기

 

 

게임 맵 최단거리

 

 

방문길이

def solution(dirs) :
    direction = ['U', 'D', 'R', 'L']
    dx = [0, 0, 1, -1]
    dy = [1, -1, 0, 0]

    x, y = 0, 0
    check = []
    for i in dirs :
        for j in range(len(direction)) :
            if i == direction[j] :
                nx = x + dx[j]
                ny = y + dy[j]            
            
        if nx > 5 or nx < -5 or ny > 5 or ny < -5 :
            continue
        
        if {(x, y), (nx, ny)} not in check :
            check.append({(x, y), (nx, ny)})
            
        x, y = nx, ny

    return len(check)

 

스킬트리

def solution(skill, skill_trees) :
    arr = list(map(str, skill))

    skill_tree = []
    for i in skill_trees :
        word = ''
        for j in i :
            if j in arr :
                word += j
        skill_tree.append(word)

    array = ['']
    for i in range(len(skill)) :
        array.append(skill[:i + 1])

    cnt = 0
    for i in skill_tree :
        if i in array :
            cnt += 1
        
    return cnt

 

모음사전

 

 

뒤에 있는 큰 수 찾기

 

 

[3차] 파일명 정렬

def solution(files) :
    arr = []
    for i in files :
        idx1 = 0
        for j in range(len(i)) :
            if i[j].isnumeric() :
                idx1 = j
                break
    
        head = i[:idx1].lower()    
        k = i[idx1:]
    
        idx2 = 0
        for j in range(len(k)) :
            if not k[j].isnumeric() :
                idx2 = j
                break
                
        if idx2 == 0 :
            idx2 = len(k)
        
        number = int(k[:idx2])
    
        arr.append([i, head, number, files.index(i)])

    arr.sort(key = lambda x : (x[1], x[2], x[3]))

    answer = []
    for i in arr :
        answer.append(i[0])
    
    return answer

 

[1차] 프렌즈4블록

 

 

롤케이크 자르기

from collections import Counter

def solution(topping) :
    left = Counter()
    right = Counter(topping)

    cnt = 0
    for i in topping :
        left[i] += 1
        right[i] -= 1
    
        if right[i] == 0 :
            del right[i]
    
        if len(left) == len(right) :
            cnt += 1
        
    return cnt

 

숫자 변환하기

 

 

2 x n 타일링

def solution(n) :
    a, b = 1, 1
    for _ in range(n) :
        a, b = b, a + b

    return a % 1000000007

 

2개 이하로 다른 비트

def solution(numbers) :
    answer = []
    for i in numbers :
        if i % 2 == 0 :
            num = bin(i)[2:]
            arr = list(num)
            arr[-1] = '1'
        else :
            num = '0' + bin(i)[2:]
            idx = num.rfind('0')
            arr = list(num)
            arr[idx] = '1'
            arr[idx + 1] = '0'
    
        answer.append(int(''.join(arr), 2))
    
    return answer

 

다리를 지나는 트럭

from collections import deque

def solution(bridge_length, weight, truck_weights) :
    truck_weights = deque(truck_weights)
    riding = deque([0] * bridge_length)
    x = 0

    time = 0
    while riding :
        time += 1
        x -= riding.popleft()
        if truck_weights :
            if x + truck_weights[0] <= weight :
                a = truck_weights.popleft()
                riding.append(a)
                x += a            
            else :
                riding.append(0)
        
    return time

 

가장 큰 수

def solution(numbers) :
    arr = []
    for i in numbers :
        arr.append([str(i), str(i) * 3])
        
    arr.sort(key = lambda x : x[1], reverse = True)
    
    answer = ''
    for i in arr :
        answer += i[0]
        
    if answer[0] == '0' :
        return '0'
    
    return answer

 

소수 찾기

from itertools import permutations

def solution(numbers) :
    arr = list(map(str, numbers))

    array = []
    for i in range(1, len(arr) + 1) :
        array.append(list(permutations(arr, i)))

    answer = []
    for i in array :
        for j in range(len(i)) :
            answer.append(''.join(i[j]))

    result = []
    for i in answer :
        result.append(int(i))
    
    sett = set(result)

    def prime_number(n) :
        if n == 0 or n == 1 :
            return False
        for i in range(2, int(n ** 0.5) + 1) :
            if n % i == 0 :
                return False
        return True

    cnt = 0
    for i in sett :
        if prime_number(i) :
            cnt += 1
        
    return cnt

 

택배상자

def solution(order) :
    stack = []

    idx = 1
    cnt = 0
    while idx < len(order) + 1 :
        stack.append(idx)
        while stack :
            if stack[-1] == order[cnt] :
                stack.pop()
                cnt += 1
            else :
                break
            
        idx += 1
            
    return cnt

 

쿼드압축 후 개수 세기

 

 

큰 수 만들기

from collections import deque

def solution(numbers, k) :
    numbers = list(map(int, numbers))

    if numbers == sorted(numbers, reverse = True) :
        answer = ''
        for i in numbers[:-k] :
            answer += str(i)
        return answer
    else :
        numbers = deque(numbers)
        stack = deque([])
        cnt = 0
        while cnt < k:
            if len(stack) == 0 :
                stack.append(numbers.popleft())
            else :
                if stack[-1] < numbers[0] :
                    stack.pop()
                    cnt += 1
                else :
                    stack.append(numbers.popleft())
        
        answer = ''
        for i in stack + numbers :
            answer += str(i)
        return answer

 

삼각달팽이

 

 

124 나라의 숫자