๐Ÿ—๏ธ Algorithm/โฌ› ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค

[Programmers] [Summer/Winter Coding(~2018)] [Python] Level1_์†Œ์ˆ˜ ๋งŒ๋“ค๊ธฐ

Dbswnstjd 2022. 3. 15. 09:58

https://programmers.co.kr/learn/courses/30/lessons/12977

 

์ฝ”๋”ฉํ…Œ์ŠคํŠธ ์—ฐ์Šต - ์†Œ์ˆ˜ ๋งŒ๋“ค๊ธฐ

์ฃผ์–ด์ง„ ์ˆซ์ž ์ค‘ 3๊ฐœ์˜ ์ˆ˜๋ฅผ ๋”ํ–ˆ์„ ๋•Œ ์†Œ์ˆ˜๊ฐ€ ๋˜๋Š” ๊ฒฝ์šฐ์˜ ๊ฐœ์ˆ˜๋ฅผ ๊ตฌํ•˜๋ ค๊ณ  ํ•ฉ๋‹ˆ๋‹ค. ์ˆซ์ž๋“ค์ด ๋“ค์–ด์žˆ๋Š” ๋ฐฐ์—ด nums๊ฐ€ ๋งค๊ฐœ๋ณ€์ˆ˜๋กœ ์ฃผ์–ด์งˆ ๋•Œ, nums์— ์žˆ๋Š” ์ˆซ์ž๋“ค ์ค‘ ์„œ๋กœ ๋‹ค๋ฅธ 3๊ฐœ๋ฅผ ๊ณจ๋ผ ๋”ํ–ˆ์„ ๋•Œ

programmers.co.kr

ํ’€์ด

# ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค 1๋‹จ๊ณ„ - ์†Œ์ˆ˜ ๋งŒ๋“ค๊ธฐ
from itertools import combinations
def check(a, b, c):
    total = a + b + c
    for i in range(2, total):
        if total % i == 0: return False
    return True

def solution(nums):
    answer = 0
    A = list(combinations(nums, 3))
    for i in A:
        if check(i[i], i[1], i[2]): answer += 1
    return answer

itertools์˜ combinations์„ ์‚ฌ์šฉํ•˜์—ฌ 3๊ฐ€์ง€๋ฅผ ์„ ํƒํ•˜๋Š” ์กฐํ•ฉ์„ ๋งŒ๋“ค๊ณ 

check ํ•จ์ˆ˜๋ฅผ ํ†ตํ•ด ์†Œ์ˆ˜์ธ์ง€ ์•„๋‹Œ์ง€ ํŒ๋ณ„


permutations / combination / product ์‚ฌ์šฉ๋ฒ•

items = ['1', '2', '3', '4', '5']
from itertools import permutations
list(permutations(items, 2))
# ๋ชจ๋“  ์ˆœ์—ด์˜ ์กฐํ•ฉ (์ˆœ์„œ๊ฐ€ ๋ฐ”๋€ ์ค‘๋ณต O)


from itertools import combinations
list(combinations(items, 2))
# ๋ชจ๋“  ์ˆœ์—ด์˜ ์กฐํ•ฉ(์ค‘๋ณต x)

from itertools import product
items = [['a', 'b', 'c,'], ['1', '2', '3', '4'], ['!', '@', '#']]
# [('a','1','!), ('a','1','@') ...]