🔅코딩테스트 공부🔅/❗백준
[백준] 2798번 블랙잭(with python)
윤무무
2023. 1. 21. 17:24
https://www.acmicpc.net/problem/2798
2798번: 블랙잭
첫째 줄에 카드의 개수 N(3 ≤ N ≤ 100)과 M(10 ≤ M ≤ 300,000)이 주어진다. 둘째 줄에는 카드에 쓰여 있는 수가 주어지며, 이 값은 100,000을 넘지 않는 양의 정수이다. 합이 M을 넘지 않는 카드 3장
www.acmicpc.net
1. 내가 작성한 코드
n,m = map(int, input().split())
num = list(map(int, input().split()))
result = []
for i in range(n):
arr = []
arr.append(num[i])
for j in range(i+1,n):
arr.append(num[j])
arr = [num[1]]
for h in range(j+1,n):
arr = [num[i],num[j]]
arr.append(num[h])
if sum(arr) <= m:
result.append(sum(arr))
print(max(result))
완전탐색을 이용해서 풀었다.
arr에 하나하나 원소를 삽입해줘서 코드가 상당히 복잡한데
n,m = map(int, input().split())
num = list(map(int, input().split()))
arr = []
for i in range(n):
for j in range(i+1,n):
for h in range(j+1,n):
result = num[i] + num[j] + num[h]
if result > m:
continue
else:
arr.append(result)
print(max(arr))
위와 같이 result 라는 변수를 통해 간략화 할 수도 있다.
2. 다른 풀이
풀고나서 구글링을 해보니 python에 있는 itertools 라이브러리를 이용해 푸는 분들이 계셨다.
=> 공식 문서 : https://docs.python.org/ko/3.8/library/itertools.html
itertools 라이브러리는 "효율적인 루핑을 위한 이터레이터를 만드는 함수"라고 한다.
이 문제에서 사용하는 건 조합(순서를 생각하지 않고 뽑는 경우의 수) 즉, combinations 이다.
from itertools import combinations
N, M = map(int, input().split())
lst = list(map(int, input().split()))
arr = []
for three in combinations(lst, 3):
if sum(three) > M:
continue
else:
arr.append(sum(three))
print(max(arr))
combinations(반복 가능한 객체, 뽑을 개수)
* 참고로 순열은 permutations(반복 가능한 개체, 뽑을 개수)이다.