[Python] ์ด๋ถ„ ํƒ์ƒ‰
ยท
Algorithm/Python
์ด๋ถ„ ํƒ์ƒ‰ ์•Œ๊ณ ๋ฆฌ์ฆ˜ def binary_search(a, x): start = 0 end = len(a) - 1 while start a[mid]: start = mid + 1 else: end = mid - 1 return -1 d = [1, 4, 9, 16, 25, 36, 49, 64, 81] print(binary_search(d, 36)) print(binary_search(d, 50)) #1 ์ค‘๊ฐ„ ์œ„์น˜๋ฅผ ์ฐพ๋Š”๋‹ค. #2 ์ฐพ๋Š” ๊ฐ’๊ณผ ์ค‘๊ฐ„ ๊ฐ’์„ ๋น„๊ตํ•œ๋‹ค. #3 ๊ฐ™๋‹ค๋ฉด ์œ„์น˜๋ฒˆํ˜ธ๋ฅผ ๋Œ๋ ค์ฃผ๊ณ  #4 ์ฐพ๋Š” ๊ฐ’์ด ์ค‘๊ฐ„ ๊ฐ’๋ณด๋‹ค ํฌ๋ฉด ์ค‘๊ฐ„ ์œ„์น˜์˜ ์˜ค๋ฅธ์ชฝ์„ ๋Œ€์ƒ์œผ๋กœ ๋‹ค์‹œ ํƒ์ƒ‰(1๋ฒˆ๋ถ€ํ„ฐ ๋‹ค์‹œ) #5 ์ฐพ๋Š” ๊ฐ’์ด ์ค‘๊ฐ„ ๊ฐ’๋ณด๋‹ค ์ž‘๋‹ค๋ฉด ์ค‘๊ฐ„ ์œ„์น˜์˜ ์™ผ์ชฝ์„ ๋Œ€์ƒ์œผ๋กœ ๋‹ค์‹œ ํƒ์ƒ‰(1๋ฒˆ๋ถ€ํ„ฐ ๋‹ค์‹œ)
[Python] ํ€ต ์ •๋ ฌ
ยท
Algorithm/Python
ํ€ต ์ •๋ ฌ ๊ธฐ์ค€ ๊ฐ’์„ ์ •ํ•˜๊ณ  ๊ธฐ์ค€๊ฐ’์— ๋งž์ถฐ ๋‚˜๋จธ์ง€ ๋ฐ์ดํ„ฐ๋“ค์˜ ์œ„์น˜๋ฅผ ๋งž์ถ”๋Š” ์•Œ๊ณ ๋ฆฌ์ฆ˜์ด๋‹ค. ํ€ต ์ •๋ ฌ ๊ณผ์ • #๊ธฐ์ค€ ๊ฐ’์„ ์ •ํ•œ๋‹ค. (ํŽธ์˜์ƒ ๋งˆ์ง€๋ง‰ ๊ฐ’์„ ๊ธฐ์ค€ ๊ฐ’์œผ๋กœ ์ •ํ•œ๋‹ค.) [2, 6, 8, 1, 5, 3, 7, 4] # ๊ธฐ์ค€ ๊ฐ’ : 4 #๊ธฐ์ค€ ๊ฐ’๋ณด๋‹ค ์ž‘์œผ๋ฉด ๊ธฐ์ค€ ๊ฐ’์˜ ์•ž์ชฝ์œผ๋กœ, ๊ธฐ์ค€ ๊ฐ’๋ณด๋‹ค ํฌ๋ฉด ๊ธฐ์ค€๊ฐ’์˜ ๋’ค๋กœ ๋ณด๋‚ธ๋‹ค. ๊ธฐ์ค€ ๊ฐ’ : 4 group1 [2, 1, 3] 4 gruop2 [6, 8, 5, 7] #์žฌ๊ท€ ํ˜ธ์ถœ์„ ์ด์šฉํ•ด ์ •๋ ฌํ•œ๋‹ค. group1 [1, 2, 3] 4 group [5, 6, 7, 8] #๋‹ค์‹œ ํ•ฉ์นœ๋‹ค. group1 + 4 + group2 ๊ฒฐ๊ณผ : [1, 2, 3, 4, 5, 6, 7, 8] ํ€ต ์ •๋ ฌ ์•Œ๊ณ ๋ฆฌ์ฆ˜ def quick_sort(a): n = len(a) #์ข…๋ฃŒ์กฐ๊ฑด if n
[Python] ๋ณ‘ํ•ฉ์ •๋ ฌ
ยท
Algorithm/Python
๋ณ‘ํ•ฉ์ •๋ ฌ ๋ฐ์ดํ„ฐ์˜ ์š”์†Œ๋“ค์„ ๋‘ ๊ทธ๋ฃน์œผ๋กœ ๋‚˜๋ˆˆ ํ›„ ์ •๋ ฌํ•˜๊ณ , ์ •๋ ฌ๋œ ๋‘ ๊ทธ๋ฃน์„ ๋น„๊ตํ•˜๋ฉฐ ํ•˜๋‚˜๋กœ ํ•ฉ์น˜๋Š” ์•Œ๊ณ ๋ฆฌ์ฆ˜์ด๋‹ค. ๋ณ‘ํ•ฉ์ •๋ ฌ๊ณผ์ • #์ˆซ์ž 8๊ฐœ๋ฅผ ๋ฐ˜์œผ๋กœ ๋‚˜๋ˆˆ๋‹ค group1 = [2, 8, 4, 7] group2 = [6, 1, 3, 5] #๋‘ ๊ทธ๋ฃน์„ ์ •๋ ฌํ•œ๋‹ค. group1 = [2, 4, 7, 8] group2 = [1, 3, 5, 6] #๋‘ ๊ทธ๋ฃน์„ ํ•˜๋‚˜์˜ ๊ทธ๋ฃน์œผ๋กœ ํ•ฉ์นœ๋‹ค. ๋‘ ๊ทธ๋ฃน์˜ ์ฒซ๋ฒˆ์งธ ๊ฐ’์„ ๋น„๊ตํ•ด ์ž‘์€ ๊ฐ’์„ ์ƒˆ๋กœ์šด ๋ฆฌ์ŠคํŠธ(result)์— ๋„ฃ๋Š”๋‹ค. group1 = [2, 4, 7, 8] group2 = [3, 5, 6] result = [1] #๋‘ ๊ทธ๋ฃน์˜ ์ฒซ๋ฒˆ์งธ ๊ฐ’์„ ๋น„๊ตํ•ด ์ž‘์€ ๊ฐ’์„ ์ƒˆ๋กœ์šด ๋ฆฌ์ŠคํŠธ์— ๋„ฃ๋Š” ๊ฒƒ์„ ๋ฐ˜๋ณตํ•œ๋‹ค. group1 = [4, 7, 8] group2 = [3, 5, 6] result ..
[Python] ์‚ฝ์ž…์ •๋ ฌ
ยท
Algorithm/Python
์‚ฝ์ž…์ •๋ ฌ ๋ฐ์ดํ„ฐ์˜ ๋ชจ๋“  ์š”์†Œ๋ฅผ ์•ž์—์„œ๋ถ€ํ„ฐ ์ฐจ๋ก€๋Œ€๋กœ ์ด๋ฏธ ์ •๋ ฌ๋œ ๋ฐฐ์—ด ๋ถ€๋ถ„๊ณผ ๋น„๊ตํ•˜์—ฌ, ์ž์‹ ์˜ ์œ„์น˜๋ฅผ ์ฐพ์•„ ์‚ฝ์ž…ํ•จ์œผ๋กœ์จ ์ •๋ ฌ์„ ์™„์„ฑํ•˜๋Š” ์•Œ๊ณ ๋ฆฌ์ฆ˜์ด๋‹ค. ์‚ฝ์ž…์ •๋ ฌ๊ณผ์ • ์˜ˆ๋ฅผ ๋“ค์–ด [2, 4, 5, 1, 3] ์ด ์žˆ์„ ๋•Œ, ์ž์‹ ์˜ ์œ„์น˜๋ฅผ ์ฐพ์•„ ๊ทธ ์œ„์น˜์— ๋“ค์–ด๊ฐ„๋‹ค. [2, 4, 5, 1, 3] # ์‹œ์ž‘ [2 | 4, 5, 1, 3] # 2๋Š” ๋งจ ์•ž์— ์œ„์น˜ํ•˜๊ธฐ ๋•Œ๋ฌธ์— ๋ฐ”๊พธ์ง€ ์•Š๋Š”๋‹ค. [2 4 | 5, 1, 3] # 4๋ถ€ํ„ฐ ๋น„๊ต, 2์˜ ๋’ค์ด๋ฏ€๋กœ ๋ฐ”๋€Œ์ง€ ์•Š๋Š”๋‹ค. [2 4 5 | 1, 3] # 5๋น„๊ต, 4์˜ ๋’ค์ด๋ฏ€๋กœ ๋ฐ”๋€Œ์ง€ ์•Š๋Š”๋‹ค. [2 4 | 5, 1, 3] # 1๋น„๊ต, 1์˜ ์ž๋ฆฌ๋Š” ๋งจ ์•ž์ด๋ฏ€๋กœ ํ•œ ์นธ์”ฉ ์˜ฎ๊ฒจ๊ฐ€๋ฉฐ 1์˜ ์ž๋ฆฌ์— 1์„ ๋„ฃ๋Š”๋‹ค. [1 2 4 5 | 3] # 3๋น„๊ต, 3์˜ ์ž๋ฆฌ๋Š” 4์™€ 5์˜ ์•ž์ด๋ฏ€๋กœ ํ•œ ์นธ์”ฉ ์˜ฎ..