개발/알고리즘
[프로그래머스] 롤케이크
개발자_티모
2024. 4. 25. 17:18
반응형
문제 이해하기
케이크를 잘라서 토핑을 공평하게 나눌 수 있는 가짓수 방법을 찾는 문제였다.
문제 해결 방법 설명하기
1. 케이크를 나누기 전 토핑의 가짓수를 계산합니다
for i in topping:
if not i in topping_right.keys():
topping_right[i] = 1
else:
topping_right[i] += 1
2.토핑을 하나씩 제거하면서 공평하게 나눠지는지를 계산합니다.
for i in topping:
if len(topping_left.keys()) == len(topping_right.keys()):
answer += 1
if not i in topping_left.keys():
topping_left[i] = 1
else:
topping_left[i] += 1
topping_right[i] -= 1
if topping_right[i] <= 0:
del topping_right[i]
코드
def solution(topping):
answer = 0
topping_left = {}
topping_right = {}
for i in topping:
if not i in topping_right.keys():
topping_right[i] = 1
else:
topping_right[i] += 1
for i in topping:
if len(topping_left.keys()) == len(topping_right.keys()):
answer += 1
if not i in topping_left.keys():
topping_left[i] = 1
else:
topping_left[i] += 1
topping_right[i] -= 1
if topping_right[i] <= 0:
del topping_right[i]
return answer
if __name__ == "__main__":
topping = [1, 2, 1, 3, 1, 4, 1, 2]
print(solution(topping)) # 10
코드 리뷰
from collections import Counter
def solution(topping):
answer = 0
dic = Counter(topping)
set_dic = set()
answer = 0
for i in topping:
dic[i] -= 1
set_dic.add(i)
if dic[i] == 0:
dic.pop(i)
if len(dic) == len(set_dic):
answer += 1
return answer
배운점 정리하기
중복을 계산할 때 Counter라는 것을 쓰면 굉장히 편하다.
https://www.daleseo.com/python-collections-counter/
파이썬 collections 모듈의 Counter 사용법
Engineering Blog by Dale Seo
www.daleseo.com
반응형