๐Ÿงฉ Algorithm/SWEA

[SWEA] 5948. ์ƒˆ์ƒ˜์ด์˜ 7-3-5 ๊ฒŒ์ž„ (Python/D3)

devCloud 2023. 11. 16. 08:03
728x90
 

SW Expert Academy

SW ํ”„๋กœ๊ทธ๋ž˜๋ฐ ์—ญ๋Ÿ‰ ๊ฐ•ํ™”์— ๋„์›€์ด ๋˜๋Š” ๋‹ค์–‘ํ•œ ํ•™์Šต ์ปจํ…์ธ ๋ฅผ ํ™•์ธํ•˜์„ธ์š”!

swexpertacademy.com


์„ค๋ช…

์„œ๋กœ ๋‹ค๋ฅธ 7๊ฐœ์˜ ์ •์ˆ˜ ์ค‘ 3๊ฐœ์˜ ์ •์ˆ˜๋ฅผ ๊ณจ๋ผ ํ•ฉ์„ ๊ตฌํ•ด์„œ ์ˆ˜๋ฅผ ๋งŒ๋“ค๋ ค๊ณ  ํ•œ๋‹ค.
์ด๋ ‡๊ฒŒ ๋งŒ๋“ค ์ˆ˜ ์žˆ๋Š” ์ˆ˜ ์ค‘์—์„œ 5๋ฒˆ์งธ๋กœ ํฐ ์ˆ˜๋ฅผ ์ถœ๋ ฅํ•œ๋‹ค.

 

ํ’€์ด

์กฐํ•ฉ(combinatinos) ์‚ฌ์šฉ

1. ๋ฐ˜๋ณต๋ฌธ์œผ๋กœ 3๊ฐœ์”ฉ ์กฐํ•ฉ์„ ๋งŒ๋“ค๊ณ  ํ•ฉ์„ ๋ฆฌ์ŠคํŠธ์— ์ €์žฅํ•œ๋‹ค.

2. sorted๋ฅผ ์‚ฌ์šฉํ•ด ๋‚ด๋ฆผ์ฐจ์ˆœ ์ •๋ ฌ์„ ํ•˜๊ณ  set์œผ๋กœ ์ค‘๋ณต์„ ์ œ๊ฑฐํ•œ๋‹ค.

3. ๋ฆฌ์ŠคํŠธ์˜ 5๋ฒˆ์งธ(์ธ๋ฑ์Šค = 4)๋ฅผ ์ถœ๋ ฅํ•œ๋‹ค.

 

โœ”๏ธ combinations

combinations ํ•จ์ˆ˜๋ฅผ ์‚ฌ์šฉํ•˜๊ธฐ ์œ„ํ•ด์„  itertools ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ๋ฅผ ๊ฐ€์ ธ์™€์•ผ ํ•œ๋‹ค.

from itertools import combinations

 

โœ”๏ธ combinations(๋ฆฌ์ŠคํŠธ, ์ •์ˆ˜)

์ •์ˆ˜ ์ž๋ฆฌ์— 3์„ ๋„ฃ์œผ๋ฉด 3๊ฐœ์˜ ์ˆซ์ž๋กœ ์กฐํ•ฉ์„ ํ•œ๋‹ค.

from itertools import combinations
n = [1, 2, 3, 4]
ans = list(combinations(n, 3))
print(ans)

#๊ฒฐ๊ณผ
[(1, 2, 3), (1, 2, 4), (1, 3, 4), (2, 3, 4)]

 

itertools์—๋Š” combinations ๋ง๊ณ ๋„ ์ˆœ์—ด(permutations)์ด ์žˆ๋Š”๋ฐ, ์กฐํ•ฉ์€ ์ˆœ์„œ๋ฅผ ๊ณ ๋ คํ•˜์ง€ ์•Š์ง€๋งŒ ์ˆœ์—ด์€ ์ˆœ์„œ๋ฅผ ๊ณ ๋ คํ•œ๋‹ค. 

 

permutaions ์‚ฌ์šฉ

from itertools import permutations
n = [1, 2, 3]
ans = list(permutations(n, 2))
print(ans)

#๊ฒฐ๊ณผ
[(1, 2), (1, 3), (2, 1), (2, 3), (3, 1), (3, 2)]

 

combinations ์‚ฌ์šฉ

from itertools import combinations, permutations
n = [1, 2, 3]
ans = list(combinations(n, 2))
print(ans)

#๊ฒฐ๊ณผ
[(1, 2), (1, 3), (2, 3)]

 

โœ”๏ธ set(list) - ์ค‘๋ณต ์ œ๊ฑฐ

n = [1, 1, 2, 2, 3]
print(set(n))

#๊ฒฐ๊ณผ
{1, 2, 3}

 

Solution

from itertools import combinations
t = int(input())
for tc in range(1, t+1):
    n = list(map(int, input().split()))
    ans = []
    for i in combinations(n, 3): #list๋กœ ์•ˆ ๋ฌถ์–ด๋„ ๋จ
        ans.append(sum(i))
    ans = list(set(sorted(ans, reverse=True))) #์ค‘๋ณต ์ œ๊ฑฐ ํ•ด์•ผ ํ•จ - set ์‚ฌ์šฉ
    print('#'+str(tc), ans[4])
728x90