본문 바로가기
Algorithm/etc

[파이썬] 프로그래머스 레벨2

by 베짱이28호 2023. 4. 2.

프로그래머스 Lv2


땅따먹기 (푸는중)

def solution(land):
    sum1,sum2,now_index1,now_index2 = 0,0,0,0
    case1,case2 = [3],[2]
    table =[]
    
    for i in range(len(land)):
        temp =[]
        for j in range(4):
            temp_sort = land[i].copy()
            temp_sort.sort()
            temp.append(land[i].index(temp_sort[j]))
        table.append(temp)

        if i==0:    
            now_index1 = table[i].index(3) # 가장 큰거 시작루트
            now_index2 = table[i].index(2) # 2번째 큰거 시작루트
        else:
            if now_index1 == table[i].index(3): # 이전층 인덱스 = 현재최대인덱스
                now_index1 = table[i].index(2) 
                case1.append(now_index1)

            else:
                now_index1 = table[i].index(3)
                case1.append(now_index1)

            if now_index2 == table[i].index(3): # 이전층 인덱스 = 현재최대인덱스
                now_index2 = table[i].index(2)
                case2.append(now_index2)
            else:
                now_index2 = table[i].index(3)
                case2.append(now_index2)

        sum1 += land[i][case1[i]]
        sum2 += land[i][case2[i]]

        answer = max(sum1,sum2)
    
    return answer

같은 열에 같은숫자 존재하는 케이스 고려 안해서 아직 못푸는중..

다이나믹 프로그래밍 공부하기


멀리뛰기

'''
import math
def solution(n):
    
    log,result = 0,0
    for i in range(0,int(n/2)+1):        
        log = math.log(math.factorial(n-i))-math.log((math.factorial(i)*math.factorial(n-2*i)))
        result += round(math.exp(log))
'''
def solution(n):
    temp = [0,1]
    for i in range(n):
        temp.append(temp[i]+temp[i+1])  
    answer = temp[n+1]%1234567
    return answer

보자마자 조합+시그마써서 바로 풀었는데 나누기에서 연산량 커서 로그값으로 계산. 

위에서 만든 함수로 나열해서 보니까 피보나치인거 알았는데 왜인지는 모르겠음

다시보니까 DP 기본중에 기본


최솟값 만들기

def solution(A,B):

    A.sort(reverse=True)
    B.sort()
    answer = sum(map(lambda x,y : x*y,A,B))
    return answer

숨바꼭질 (1697) - 실버1 이랑 똑같은 문제


피보나치 수

def solution(n):
    temp = [0,1]
    for i in range(n):
        temp.append(temp[i]+temp[i+1])  
    answer = temp[n]%1234567
    return answer

행렬의 곱셈

def solution(arr1,arr2):
    answer =[]
    h1,w1 = len(arr1),len(arr1[0])
    h2,w2 = len(arr2),len(arr2[0])
    if w1 != h2 :
        for i in range(h1):
            temp = []
            for j in range(w2):
                count = 0
                for k in range(w1):            
                    count += arr1[i][k]*arr2[j][k]
                temp.append(count)
            answer.append(temp)

    for i in range(h1):
        temp = []
        for j in range(w2):
            count = 0
            for k in range(w1):            
                count += arr1[i][k]*arr2[k][j]
            temp.append(count)
        answer.append(temp)
    return answer

넘파이쓰면 10초컷..

댓글