Coding Test/programmers

[Python] 파이썬 프로그래머스 귤 고르기

파송송 2023. 2. 27. 11:29
728x90

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

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr


나의 풀이

  •  [1, 3, 2, 5, 4, 5, 2, 3]의 크기를 가진 귤을 6개 팔아야 하고 귤의 크기가 일정한 것 끼리 담아야 할 때 (2, 3, 5) 총 3가지 귤의 크기로 담을 수 있음
  • dict을 사용하여 귤의 크기의 개수를 초기화하였음
귤 크기 귤 개수
1 1
2 2
3 2
4 1
5 2
  • dict의 items()를 사용하여 tuple로 가져올 수 있고 이를 귤 개수로 sort하여 내림차순함
[(3, 2), (2, 2), (5, 2), (1, 1), (4, 1)]
  • 귤 개수를 cnt 하여 k보다 커질 때 귤의 종류를 return 함
def solution(k, tangerine):
    answer = 0
    cnt = 0
    
    tan_dict = dict()
    
    for i in tangerine:
        if tan_dict.get(i) == None:
            tan_dict[i] = 1
        else:
            tan_dict[i] += 1

    tan_cnt = sorted(tan_dict.items(), key=lambda x : x [1], reverse=True)
    
    for (i, j) in tan_cnt:
        if answer < k:
            answer += j
            cnt += 1
        else:
            break
    return cnt

다른 사람의 풀이

collections Counter

  • collections의 Counter를 사용하면 요소의 개수를 dict으로 return 해줌
Counter({3: 2, 2: 2, 5: 2, 1: 1, 4: 1})
  • values로 내림차순 sort를 하여 계산함
import collections
def solution(k, tangerine):
    answer = 0
    cnt = collections.Counter(tangerine)
    print(cnt)

    for v in sorted(cnt.values(), reverse = True):
        k -= v
        answer += 1
        if k <= 0:
            break
    return answer

 

items()를 사용하지 말고 values()를 사용하면 더 빠르게 코드를 작성할 수 있음


코드 수정

def solution(k, tangerine):
    answer = 0
    cnt = 0
    
    tan_dict = dict()
    
    for i in tangerine:
        if tan_dict.get(i) == None:
            tan_dict[i] = 1
        else:
            tan_dict[i] += 1

    tan_cnt = sorted(tan_dict.values(), reverse = True)
    for i in tan_cnt:
        k -= i
        answer += 1
        if k <= 0:
            break
            
    return answer

728x90