[ Code Kata ] ๐Ÿคฏ Python #3 ์ค‘๋ณต๋˜์ง€ ์•Š๋Š” ๊ฐ€์žฅ ๊ธด ๋ฌธ์ž์—ด ์ถ”์ถœํ•˜๊ธฐ / Enumerate( ) ํ•จ์ˆ˜

Haileeยท2020๋…„ 12์›” 2์ผ
0

[ Code Kata ]

๋ชฉ๋ก ๋ณด๊ธฐ
9/28
post-thumbnail

Enumerate( ) ์‚ฌ์šฉํ•˜๊ธฐ

๋ฌธ์ œ

String ํ˜•์ธ str ์ธ์ž์—์„œ ์ค‘๋ณต๋˜์ง€ ์•Š์€ ์•ŒํŒŒ๋ฒณ์œผ๋กœ ์ด๋ฃจ์–ด์ง„ ์ œ์ผ ๊ธด ๋‹จ์–ด์˜ ๊ธธ์ด๋ฅผ ๋ฐ˜ํ™˜ํ•ด์ฃผ์„ธ์š”.

str: ํ…์ŠคํŠธ
return: ์ค‘๋ณต๋˜์ง€ ์•Š์€ ์•ŒํŒŒ๋ฒณ ๊ธธ์ด (์ˆซ์ž ๋ฐ˜ํ™˜)
str: ํ…์ŠคํŠธ
return: ์ค‘๋ณต๋˜์ง€ ์•Š์€ ์•ŒํŒŒ๋ฒณ ๊ธธ์ด (์ˆซ์ž ๋ฐ˜ํ™˜)

์˜ˆ๋ฅผ ๋“ค์–ด,

str = "abcabcabc"
return์€ 3
=> 'abc' ๊ฐ€ ์ œ์ผ ๊ธธ๊ธฐ ๋•Œ๋ฌธ

str = "abcabcabc"
return์€ 3
=> 'abc' ๊ฐ€ ์ œ์ผ ๊ธธ๊ธฐ ๋•Œ๋ฌธ

str = "aaaaa"
return์€ 1
=> 'a' ๊ฐ€ ์ œ์ผ ๊ธธ๊ธฐ ๋•Œ๋ฌธ

str = "aaaaa"
return์€ 1
=> 'a' ๊ฐ€ ์ œ์ผ ๊ธธ๊ธฐ ๋•Œ๋ฌธ

str = "sttrg"
return์€ 3
=> 'trg' ๊ฐ€ ์ œ์ผ ๊ธธ๊ธฐ ๋•Œ๋ฌธ

์˜ค๋Š˜์˜ ๋ฌธ์ œ๋Š” ๋„์ €ํžˆ ์ดํ•ด๊ฐ€ ๊ฐ€์ง€ ์•Š์•˜๋‹ค.
enumerate( )๋ผ๋Š” ํŒŒ์ด์ฌ ๋‚ด์žฅ ํ•จ์ˆ˜๋ฅผ ์•Œ์ง€ ๋ชปํ–ˆ๊ธฐ ๋•Œ๋ฌธ..!!!


model solution

def get_len_of_str(s):
	dct = {}
	max_so_far = curr_max = start = 0
	for index, i in enumerate(s):
		if i in dct and dct[i] >= start:
			max_so_far = max(max_so_far, curr_max)
			curr_max = index - dct[i]
			start = dct[i] + 1
		else:
			curr_max += 1
		dct[i] = index
	return max(max_so_far, curr_max)

enumerate( )

๊ทธ๋ ‡๋‹ค๋ฉด ๊ณผ์—ฐ ์ด ๋‚ด์žฅํ•จ์ˆ˜๋Š” ์–ด๋–ค ์—ญํ• ์„ ํ•˜๋Š” ๊ฒƒ์ผ๊นŒ? ๋„์ €ํžˆ ์–ด๋–ค ์—ญํ• ์„ ํ•˜๋Š”์ง€ ๊ฐ์ด ์˜ค์ง€๋ฅผ ์•Š๋Š” ํ•จ์ˆ˜..!

enumerate๋Š” "์—ด๊ฑฐํ•˜๋‹ค"๋ผ๋Š” ๋œป์ด๋‹ค. ์ด ํ•จ์ˆ˜๋Š” ์ˆœ์„œ๊ฐ€ ์žˆ๋Š” ์ž๋ฃŒํ˜•(๋ฆฌ์ŠคํŠธ, ํŠœํ”Œ, ๋ฌธ์ž์—ด)์„ ์ž…๋ ฅ์œผ๋กœ ๋ฐ›์•„ ์ธ๋ฑ์Šค ๊ฐ’์„ ํฌํ•จํ•˜๋Š” enumerate ๊ฐ์ฒด๋ฅผ ๋Œ๋ ค์ค€๋‹ค.

โ€ป ๋ณดํ†ต enumerate ํ•จ์ˆ˜๋Š” ๋‹ค์Œ ์˜ˆ์ œ์ฒ˜๋Ÿผ for๋ฌธ๊ณผ ํ•จ๊ป˜ ์ž์ฃผ ์‚ฌ์šฉํ•œ๋‹ค.

์ž˜ ์ดํ•ด๋˜์ง€ ์•Š์œผ๋ฉด ๋‹ค์Œ ์˜ˆ๋ฅผ ๋ณด์ž.

for i, name in enumerate(['body', 'foo', 'bar']):
    print(i, name)
...
0 body
1 foo
2 bar

์ˆœ์„œ ๊ฐ’๊ณผ ํ•จ๊ป˜ body, foo, bar๊ฐ€ ์ˆœ์„œ๋Œ€๋กœ ์ถœ๋ ฅ๋˜์—ˆ๋‹ค.
์ฆ‰ ์œ„ ์˜ˆ์ œ์™€ ๊ฐ™์ด enumerate๋ฅผ for๋ฌธ๊ณผ ํ•จ๊ป˜ ์‚ฌ์šฉํ•˜๋ฉด ์ž๋ฃŒํ˜•์˜ ํ˜„์žฌ ์ˆœ์„œ(index)์™€ ๊ทธ ๊ฐ’์„ ์‰ฝ๊ฒŒ ์•Œ ์ˆ˜ ์žˆ๋‹ค.

for๋ฌธ์ฒ˜๋Ÿผ ๋ฐ˜๋ณต๋˜๋Š” ๊ตฌ๊ฐ„์—์„œ ๊ฐ์ฒด๊ฐ€ ํ˜„์žฌ ์–ด๋Š ์œ„์น˜์— ์žˆ๋Š”์ง€ ์•Œ๋ ค ์ฃผ๋Š” ์ธ๋ฑ์Šค ๊ฐ’์ด ํ•„์š”ํ• ๋•Œ enumerate ํ•จ์ˆ˜๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด ๋งค์šฐ ์œ ์šฉํ•˜๋‹ค.

profile
์›น ๊ฐœ๋ฐœ ๐Ÿท๐Ÿ˜Ž๐Ÿ‘Š๐Ÿป๐Ÿ”ฅ

0๊ฐœ์˜ ๋Œ“๊ธ€