[Python] ์„ ํƒ์ •๋ ฌ
ยท
Algorithm/Python
์„ ํƒ์ •๋ ฌ ๋ฐ์ดํ„ฐ์—์„œ ์ตœ์†Ÿ๊ฐ’์„ ์ฐพ์•„ ๊ทธ ๊ฐ’๊ณผ ๋ฒ”์œ„์˜ ๋งจ ์•ž์— ์žˆ๋Š” ๊ฐ’์„ ์„œ๋กœ ๋ฐ”๊พธ๋Š” ๊ณผ์ •์„ ๋ฐ˜๋ณตํ•˜๋Š” ์•Œ๊ณ ๋ฆฌ์ฆ˜์ด๋‹ค. ์„ ํƒ์ •๋ ฌ ๊ณผ์ • ์˜ˆ๋ฅผ ๋“ค์–ด [2, 4, 5, 1, 3] ๊ฐ€ ์žˆ์„ ๋•Œ, ๊ฐ€์žฅ ์ž‘์€ ๊ฐ’์„ ์ฐพ์•„ ์ฒซ๋ฒˆ์งธ ๊ฐ’๊ณผ ๊ทธ ๊ฐ’์„ ๋ฐ”๊พผ๋‹ค. (์ด๋ฏธ ์ •๋ ฌ ์™„๋ฃŒ๋œ ๊ฐ’์€ | ๋กœ ๊ตฌ๋ถ„ํ•œ๋‹ค.) [2, 4, 5, 1, 3] # ๊ฐ€์žฅ ์ž‘์€ ๊ฐ’ : 1 ์ฒซ๋ฒˆ์งธ ๊ฐ’ : 2 [1 | 4, 5, 2, 3] # ๊ฐ€์žฅ ์ž‘์€ ๊ฐ’ : 2 ์ฒซ๋ฒˆ์งธ ๊ฐ’ : 4 [1, 2 | 5, 4, 3] # ๊ฐ€์žฅ ์ž‘์€ ๊ฐ’ : 3 ์ฒซ๋ฒˆ์งธ ๊ฐ’ : 5 [1, 2, 3 | 4, 5] # ๊ฐ€์žฅ ์ž‘์€ ๊ฐ’ : 4 ์ฒซ๋ฒˆ์งธ ๊ฐ’ : 4 //๋ณ€ํ™”์—†์Œ [1, 2, 3, 4 | 5] # ์ž๋ฃŒ๊ฐ€ 5 ํ•˜๋‚˜๋งŒ ๋‚จ์Œ. ์ข…๋ฃŒ ๊ฒฐ๊ณผ [1, 2, 3, 4, 5] ์„ ํƒ์ •๋ ฌ ์•Œ๊ณ ๋ฆฌ์ฆ˜ def sel_..
[Python] ์ˆœ์ฐจํƒ์ƒ‰
ยท
Algorithm/Python
๋ฆฌ์ŠคํŠธ์—์„œ ํŠน์ •๊ฐ’์„ ์ฐพ์•„ ๊ทธ ๊ฐ’์˜ ์œ„์น˜๋ฅผ ๋Œ๋ ค์ฃผ๋Š” ํ”„๋กœ๊ทธ๋žจ def search_list(a, x): n = len(a) for i in range(n): if x == a[i]: return i return -1 v = [20, 19, 11, 27, 3] print(search_list(v, 11)) ๊ฒฐ๊ณผ : 2 ์ฒซ ๋ฒˆ์งธ ๊ฐ’๋ถ€ํ„ฐ ์ˆœ์„œ๋Œ€๋กœ ๋น„๊ตํ•œ๋‹ค. ๋งŒ์•ฝ 11์„ ์ฐพ์„ ๊ฒฝ์šฐ ๊ทธ ์œ„์น˜๋ฅผ ๋Œ๋ ค์ค€๋‹ค. *3๋ฒˆ์งธ์ธ ๊ฒƒ ๊ฐ™์ง€๋งŒ 0๋ถ€ํ„ฐ ์ˆซ์ž๋ฅผ ์„ธ๊ธฐ ๋•Œ๋ฌธ์— 2๋ฅผ ๋Œ๋ ค์ค€๋‹ค.
[Python] ์ตœ๋Œ€๊ณต์•ฝ์ˆ˜ ๊ตฌํ•˜๊ธฐ
ยท
Algorithm/Python
์ฒซ ๋ฒˆ์งธ ๋ฐฉ๋ฒ• def gcd(a, b): i = min(a, b) #1 while True: if a % i == 0 and b % i == 0: # 2 return i #3 i -= 1 #4 print(gcd(60, 24)) 1. ๋‘ ์ˆ˜ ์ค‘์— ๋” ์ž‘์€ ์ˆ˜๋ฅผ i์— ์ €์žฅํ•œ๋‹ค. 2. i๊ฐ€ ๋‘ ์ˆ˜์˜ ๊ณตํ†ต๋œ ์•ฝ์ˆ˜์ธ์ง€ ํ™•์ธํ•œ๋‹ค. 3. ๋งŒ์•ฝ ๊ณตํ†ต๋œ ์•ฝ์ˆ˜๋ผ๋ฉด ๊ฒฐ๊ณผ๊ฐ’์„ ๋Œ๋ ค์ฃผ๊ณ  ์ข…๋ฃŒํ•œ๋‹ค. 4. ์•„๋‹ˆ๋ผ๋ฉด i๋ฅผ 1 ๊ฐ์†Œ์‹œํ‚ค๊ณ  2๋ฒˆ์œผ๋กœ ๋Œ์•„๊ฐ€ ๋ฐ˜๋ณตํ•œ๋‹ค. ๋‘ ๋ฒˆ์งธ ๋ฐฉ๋ฒ• def gcd(a, b): if b == 0: return a return gcd(b, a % b) print(gcd(60, 24)) ์ด ๋ฐฉ๋ฒ•์€ ์œ ํด๋ฆฌ๋“œ ์•Œ๊ณ ๋ฆฌ์ฆ˜์„ ์ด์šฉํ•œ ๋ฐฉ๋ฒ•์ด๋‹ค. a์™€ b์˜ ์ตœ๋Œ€๊ณต์•ฝ์ˆ˜๋Š” 'b'์™€ 'a๋ฅผ b๋กœ ๋‚˜๋ˆˆ ๋‚˜๋จธ์ง€'์˜ ์ตœ๋Œ€๊ณต์•ฝ์ˆ˜์™€ ๊ฐ™๋‹ค..
[Python] ํŒฉํ† ๋ฆฌ์–ผ ๊ตฌํ•˜๊ธฐ
ยท
Algorithm/Python
์ฒซ ๋ฒˆ์งธ ๋ฐฉ๋ฒ• def fact(n): f = 1 for i in range(1, n+1): f *= i return f print(fact(5)) for๋ฌธ์„ ์‚ฌ์šฉํ•˜์—ฌ ํŒฉํ† ๋ฆฌ์–ผ์„ ๊ตฌํ•˜๋Š” ๋ฐฉ๋ฒ•์ด๋‹ค. ๋‘ ๋ฒˆ์งธ ๋ฐฉ๋ฒ• def fact(n): if n