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

โฌ› [Programmers] [Python] [Level1] ๋ฌธ์ž์—ด ๋‚ด ๋งˆ์Œ๋Œ€๋กœ ์ •๋ ฌํ•˜๊ธฐ

Dbswnstjd 2023. 4. 10. 11:40

๋ฌธ์ œ

https://school.programmers.co.kr/learn/courses/30/lessons/12915

 

ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค

์ฝ”๋“œ ์ค‘์‹ฌ์˜ ๊ฐœ๋ฐœ์ž ์ฑ„์šฉ. ์Šคํƒ ๊ธฐ๋ฐ˜์˜ ํฌ์ง€์…˜ ๋งค์นญ. ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค์˜ ๊ฐœ๋ฐœ์ž ๋งž์ถคํ˜• ํ”„๋กœํ•„์„ ๋“ฑ๋กํ•˜๊ณ , ๋‚˜์™€ ๊ธฐ์ˆ  ๊ถํ•ฉ์ด ์ž˜ ๋งž๋Š” ๊ธฐ์—…๋“ค์„ ๋งค์นญ ๋ฐ›์œผ์„ธ์š”.

programmers.co.kr

ํ’€์ด

# ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค 1๋‹จ๊ณ„ - ๋ฌธ์ž์—ด ๋‚ด ๋งˆ์Œ๋Œ€๋กœ ์ •๋ ฌํ•˜๊ธฐ
def solution(strings, n):
    return sorted(strings, key = lambda x: (x[n], x))

print(solution(["abce", "abcd", "cdx"], 2))
print(solution(["sun", "bed", "car"], 1))

๋งจ ์ฒ˜์Œ ๋ฌธ์ œ๋ฅผ ํ’€์—ˆ์„ ๋•Œ sorted(strings, key=lambda x: x[n]) ์œผ๋กœ ํ’€์—ˆ๋Š”๋ฐ ์ด๋Š” ์ธ๋ฑ์Šค๋ฅผ ๊ธฐ์ค€์œผ๋กœ ์ •๋ ฌํ•ด์ฃผ๋ฏ€๋กœ ๋ฌธ์ œ์˜ ์กฐ๊ฑด๊ณผ ๊ฐ’์ด ๋‹ค๋ฅด๊ฒŒ ๋œ๋‹ค. 

๋”ฐ๋ผ์„œ ๋จผ์ € strings๋ฅผ ์ •๋ ฌ ํ•ด์ฃผ๊ณ  ๋‚œ ํ›„ x[n]์— ๋Œ€ํ•ด์„œ ์ •๋ ฌ์„ ๋‹ค์‹œ ํ•ด์ฃผ๋„๋ก ํ•œ๋‹ค.