[백준] 2798: 블랙잭 - 파이썬[python]

다인·2024년 9월 1일

백준

목록 보기
48/112
post-thumbnail

나는 간단히 삼중 반복문으로 풀었는데, 구글링을 해보니까 파이썬의 itertools라는 라이브러리를 이용해서 푸는 방법도 있길래 정리해본당

1. 삼중 for문

N, M = map(int, input().split())
num = list(map(int, input().split()))
max = 0

for i in range(N-2):
    for j in range(i+1, N-1):
        for k in range(j+1, N):
            sum = num[i] + num[j] + num[k]
            if sum <= M and sum > max:
                max = sum

print(max)
  • 나는 조건문에
sum <= M and sum > max

이렇게 한 번에 썼는데,

if sum > M:
	continue
else:
	result = max(result, sum)

이렇게 많이 쓰더랑!

2. combinations

from itertools import combinations

N, M = map(int, input().split())
num = list(map(int, input().split()))
result = 0

for three in combinations(num, 3):
    if sum(three) <= M and sum(three) > result:
        result = sum(three)

print(result)
  • combinations는 말 그대로 확통 때 배운 조합이다.
  • 그래서 순서를 고려하지 않고(AB = BA) 개수만큼 뽑는다.
    ex) 다음의 결과는 ['AB', 'BC', 'CA']
lst = ['A', 'B', 'C']
print(list(map(''.join, itertools.combinations(lst, 2))))
  • 순서를 고려하고 싶다면 permutations를 이용하면 된다!

결과

0개의 댓글