[python ๊ธฐ์ดˆ] code-kata week1-3

EMMAยท2022๋…„ 3์›” 20์ผ
0

[wecode] Code-kata

๋ชฉ๋ก ๋ณด๊ธฐ
3/12

๐Ÿ–ฅ Code-kata week1-3


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

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

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

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

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


ํ’€์ด

์ด ๋ฌธ์ œ์˜ ๊ฒฝ์šฐ, ํ•ต์‹ฌ์€ nested for๋ฌธ์ด๋‹ค.
๋ฐ˜ํ™˜ํ•ด์•ผ ํ•˜๋Š” ๊ฐ’์€ ์ค‘๋ณต๋˜๋Š” ๋ฌธ์ž๊ฐ€ ์—†๋Š” ๋ฌธ์ž์—ด์˜ ์ตœ๋Œ€๊ธธ์ด๋‹ค.
๊ทธ๋ฆฌ๊ณ  ์ฒซ ๋ฒˆ์งธ ๋ฌธ์ž๋ถ€ํ„ฐ ์‹œ์ž‘ํ•ด์„œ ์•ˆ์ชฝ for๋ฌธ์„ ํ†ตํ•ด ํ•œ๋ฒˆ ๋Œ๊ณ ,
๋ฐ”๊นฅ for๋ฌธ์„ ํ†ตํ•ด ๋‘ ๋ฒˆ์งธ ๋ฌธ์ž์—ด๋ถ€ํ„ฐ ๋˜ ๋ˆ๋‹ค.

def get_len_of_str(s):
	N = len(s)
    max_length = 0

์šฐ์„  ์ธ์ž์˜ ์ „์ฒด ๊ธธ์ด๋ฅผ N์— ๋‹ด๋Š”๋‹ค.
๊ทธ๋ฆฌ๊ณ  ์ค‘๋ณต์—†๋Š” ๋ฌธ์ž์—ด์˜ ์ตœ๋Œ€๊ธธ์ด๋ฅผ ๋‹ด์„ max_length์— 0์„ ๋‹ด์•„์ค€๋‹ค. 0์„ ๋‹ด๋Š” ์ด์œ ๋Š”, ์–ด๋–ค ์ธ์ž์ด๋“  ๋ฌธ์ž์—ด ๊ธธ์ด์˜ ์ตœ์†Œ๊ฐ’์€ 1์ด๊ธฐ ๋•Œ๋ฌธ.
์ค‘๋ณต๋˜์ง€ ์•Š๋Š” ๋ฌธ์ž์—ด์„ ๋‹ด์•„์ค„ ๋ณ€์ˆ˜ result๋Š” for๋ฌธ ์•ˆ์— ์ž‘์„ฑํ•œ๋‹ค.

def get_len_of_str(s):
	N = len(s)
    max_length = 0
    for i in range(N-1):
    	result = s[i]
    	for j in range(i+1,N):
        	if s[j] in result: break
            else: result += s[j]
        max_length = max(max_length, len(result))
        
    return max_length 

๋ช‡ ๊ฐ€์ง€ point

  • max_length=max(max_length, len(result))์™€ ๊ฐ™์ด ์“ฐ๋ฉด, if๋ฌธ์„ ์•ˆ์จ๋„ ๋œ๋‹ค.
  • ๋‚ด๊ฐ€ ๊ตฌํ•˜๊ณ ์ž ํ•˜๋Š” ๊ฐ’์ด ์ตœ๋Œ€๊ฐ’์ธ์ง€ ์ตœ์†Œ๊ฐ’์ธ์ง€ ๋จผ์ € ์ƒ๊ฐํ•ด์•ผ ํ•œ๋‹ค. (๋งŒ์•ฝ ์ตœ์†Œ๊ฐ’ ๊ตฌํ•˜๋Š”๋ฐ ์ดˆ๊ธฐ๊ฐ’์„ 0์œผ๋กœ ์žก์œผ๋ฉด return๊ฐ’์€ ๊ณ„์† 0)
profile
์˜ˆ๋น„ ๊ฐœ๋ฐœ์ž์˜ ๊ธฐ์ˆ  ๋ธ”๋กœ๊ทธ | explore, explore and explore

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