chyam

[프로그래머스 Lv2,python] - 시소 짝꿍 본문

프로그래머스/LV2

[프로그래머스 Lv2,python] - 시소 짝꿍

chyam_eun 2025. 2. 23. 14:39

https://school.programmers.co.kr/learn/courses/30/lessons/152996

 

프로그래머스

SW개발자를 위한 평가, 교육, 채용까지 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프

programmers.co.kr

from collections import Counter

def solution(weights):
    cnt=0
    weight_count=Counter(weights)  # 무게별 개수 저장

    for w, c in weight_count.items(): # 동일한 무게 쌍 처리
        if c>1:
            cnt+=c*(c-1)//2 # 조합으로 개수 더해주기

    ratios=[(2, 3), (1, 2), (3, 4)] # 가능한 비율 쌍 탐색
    for w in weights:
        for a, b in ratios:
            if (w*b)%a==0:  # 나누어떨어질 때만 탐색
                target=(w*b)//a
                if target in weight_count:
                    cnt+=weight_count[target]

    return cnt

 

아래코드는 시간초과가 걸렸던 코드이다. 

def list_append(a,b,li):
    if a==b:
        li.append([a,b])
    else:
        for i in range(2,5):
            for j in range(2,5):
                li.append([a*i,b*j]) # 비율 생각안하고 2~4 곱한값들 추가하기
        
def solution(weights):
    li=[]
    cnt=0
    start,end=0,1
    while(start<len(weights) and end<len(weights)):
        list_append(weights[start],weights[end],li) # 두개의 원소 접근
        end+=1
        if end>=len(weights):
            start+=1
            end=start+1
    for i in li:
        if i[0]==i[1]: # 저장된 값이 같을 때
            cnt+=1
    return cnt