๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
4๏ธโƒฃ Python/Problem Solving

[Python Algorithm] ์ตœ์†Ÿ๊ฐ’ ๋งŒ๋“ค๊ธฐ Programmers(Lv.2)

by seolhee2750 2022. 2. 4.
๋ฌธ์ œ

https://programmers.co.kr/learn/courses/30/lessons/12941?language=python3 

 

์ฝ”๋”ฉํ…Œ์ŠคํŠธ ์—ฐ์Šต - ์ตœ์†Ÿ๊ฐ’ ๋งŒ๋“ค๊ธฐ

๊ธธ์ด๊ฐ€ ๊ฐ™์€ ๋ฐฐ์—ด A, B ๋‘๊ฐœ๊ฐ€ ์žˆ์Šต๋‹ˆ๋‹ค. ๊ฐ ๋ฐฐ์—ด์€ ์ž์—ฐ์ˆ˜๋กœ ์ด๋ฃจ์–ด์ ธ ์žˆ์Šต๋‹ˆ๋‹ค. ๋ฐฐ์—ด A, B์—์„œ ๊ฐ๊ฐ ํ•œ ๊ฐœ์˜ ์ˆซ์ž๋ฅผ ๋ฝ‘์•„ ๋‘ ์ˆ˜๋ฅผ ๊ณฑํ•ฉ๋‹ˆ๋‹ค. ์ด๋Ÿฌํ•œ ๊ณผ์ •์„ ๋ฐฐ์—ด์˜ ๊ธธ์ด๋งŒํผ ๋ฐ˜๋ณตํ•˜๋ฉฐ, ๋‘ ์ˆ˜๋ฅผ ๊ณฑ

programmers.co.kr

 

๋‚ด ๋ฌธ์ œ ํ’€์ด
def solution(A,B):
    answer = 0
    A.sort()
    B.sort(reverse = True)
    
    for i in range(len(A)):
        answer += (A[i] * B[i])
    
    return answer

๐Ÿ‘‰ ๊ตฌํ˜„ ๋ฌธ์ œ๋กœ, ์ตœ์†Ÿ๊ฐ’์„ ๋งŒ๋“œ๋Š” ๋ฐฉ๋ฒ•๋งŒ ์•Œ๋ฉด ํ’€ ์ˆ˜ ์žˆ๋Š” ๋ฌธ์ œ

ํ•œ ๋ฆฌ์ŠคํŠธ์˜ ๊ฐ€์žฅ ์ž‘์€ ๊ฐ’๊ณผ ๋˜ ๋‹ค๋ฅธ ๋ฆฌ์ŠคํŠธ์˜ ๊ฐ€์žฅ ํฐ ๊ฐ’์„ ๊ณฑํ•ด์ฃผ๋ฉด ๊ฐ€์žฅ ์ž‘์€ ๊ฐ’์„ ์•Œ ์ˆ˜ ์žˆ๋‹ค.

 

์ธ์ƒ์ ์ธ ํ’€์ด
def solution(A,B):
    return sum(a*b for a, b in zip(sorted(A), sorted(B, reverse = True)))

 

๐Ÿ’ก ํ”ผ๋“œ๋ฐฑ
  • ์˜ค๋žœ๋งŒ์— ๋‹ค๋ฅธ ์‚ฌ๋žŒ์˜ ํ’€์ด ์ค‘ ์ธ์ƒ์ ์ธ ํ’€์ด๋ฅผ ์ถ”๊ฐ€ํ–ˆ๋Š”๋ฐ,
    zip์„ swift์—์„œ๋Š” ๋ช‡ ๋ฒˆ ์จ๋ดค๋Š”๋ฐ python์—์„œ๋„ ์ด๋ ‡๊ฒŒ ์“ธ ์ˆ˜ ์žˆ๋Š”์ง€ ์ฒ˜์Œ ์•Œ์•˜๋‹ค.
    ๊ทธ๋ฆฌ๊ณ  for๋ฌธ์—์„œ ์ธ์ž๋ฅผ ๋‘ ๊ฐ€์ง€ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋‹ค๋Š” ๊ฒƒ๋„,,!

๋Œ“๊ธ€