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

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

[wecode] Code-kata

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

๐Ÿ–ฅ Code-kata week1-4


๋ฌธ์ œ
strs์€ ๋‹จ์–ด๊ฐ€ ๋‹ด๊ธด ๋ฐฐ์—ด์ž…๋‹ˆ๋‹ค.
๊ณตํ†ต๋œ ์‹œ์ž‘ ๋‹จ์–ด(prefix)๋ฅผ ๋ฐ˜ํ™˜ํ•ด์ฃผ์„ธ์š”.
์˜ˆ๋ฅผ ๋“ค์–ด

strs = ['start', 'stair', 'step']
return์€ 'st'
strs = ['start', 'wework', 'today']
return์€ ''


ํ’€์ด
๋‚ด๊ฐ€ ์ฒ˜์Œ์— ์ ‘๊ทผํ•œ ๋ฐฉ์‹์€ set ์ž๋ฃŒํ˜•์„ ํ™œ์šฉํ•˜๋Š” ๊ฒƒ์ด์—ˆ๋‹ค.
list๋ฅผ set์œผ๋กœ ๋ฐ”๊พธ๋ฉด ์ค‘๋ณต๊ฐ’์ด ์ œ๊ฑฐ๋œ๋‹ค๋Š” ์ ์„ ํ™œ์šฉํ•ด,
๊ฐ ๋‹จ์–ด ๋ณ„ ๋ฌธ์ž๋ฅผ list๋กœ ๋ฌถ๊ณ  set์œผ๋กœ ๋ฐ”๊ฟจ์„ ๋•Œ ๊ธธ์ด๊ฐ€ 1์ด๋ฉด
-> ๋ชจ๋‘ ๊ฐ™์€ ๋ฌธ์ž๋ผ๋Š” ๋œป์ด๋‹ค.

strs = ['start','stair','step']

def get_prefix(strs):
  result = ''
  min_length = min([len(str) for str in strs])

  #for๋ฌธ์„ ํ†ตํ•ด ์•„๋ž˜์™€ ๊ฐ™์ด new_lst๋ฅผ ๋งŒ๋“ค๊ณ , ๋น„๊ต๊ฐ€ ๋๋‚œ ํ›„์—๋Š” slicing์„ ํ†ตํ•ด ์ฒซ ๋ฌธ์ž๋ฅผ ์‚ญ์ œํ•œ๋‹ค. 
  new_lst = [strs[0][0], strs[1][0], strs[2][0]]
  strs[i] = strs[1:]	#['tart','tair','tep']
  new_lst = [strs[0][0], strs[1][0], strs[2][0]]
  strs[i] = strs[1:]	#['art','air','ep']
  ...
  ...

  while min_length != 0: 
      if set(new_lst) == 1:
          #return๊ฐ’์— ์ €์žฅํ•˜๊ณ  ๋‹ค์Œ ๋ฌธ์ž๋กœ ๋„˜์–ด๊ฐ„๋‹ค
          ...

๊ทธ๋Ÿฐ๋ฐ ์ด๋ ‡๊ฒŒ ํ–ˆ๋”๋‹ˆ ๋ช‡ ๊ฐ€์ง€ ๋ฌธ์ œ์ ์ด ์žˆ์—ˆ๋‹ค.

  • ์ด์ค‘๋ฐฐ์—ด์„ ํ•œ๋ฒˆ ๋Œ๋ฆฌ๊ณ ๋‚˜์„œ for๋ฌธ์„ ์ตœ๋Œ€ํ•œ ๋‹จ์ˆœํ•˜๊ฒŒ ๋งŒ๋“ค๊ณ ์ž ์ฒซ ๋ฒˆ์งธ ๋ฌธ์ž๋ฅผ ์ž˜๋ผ๋‚ด๋Š” slicing ๋ฐฉ๋ฒ•์„ ์‚ฌ์šฉํ•ด์•ผ ํ–ˆ๊ณ ,
  • indexing์„ ์‚ฌ์šฉํ•˜๋‹ค๋ณด๋‹ˆ ์ผ๋ถ€ ๋ฌธ์ž์—ด์ด ''์ด ๋˜์–ด๋ฒ„๋ฆฌ๋Š” ๊ฒฝ์šฐ error๊ฐ€ ๋ฐœ์ƒํ–ˆ๋‹ค.
  • ๋„ˆ๋ฌด ๋ชจ๋“  ๋‚ด์šฉ์„ ํ•œ ์กฐ๊ฑด๋ฌธ/While๋ฌธ ๋“ฑ ์•ˆ์— ํ‘œํ˜„ํ•˜๋ ค๊ณ  ํ•˜๋‹ค๋ณด๋‹ˆ, ์˜คํžˆ๋ ค ์ฝ”๋”ฉ์ด ๋ณต์žกํ•ด์กŒ๋‹ค.

๊ทธ๋ž˜์„œ ๋‹ค์‹œ ์ƒ๊ฐํ•œ ๋ฐฉ์‹์€,

  • ๋ฐœ์ƒํ•  ์ˆ˜ ์žˆ๋Š” ๊ฒฝ์šฐ์˜ ์ˆ˜๋ฅผ ๋ธ”๋Ÿญํ™” ํ•œ๋‹ค.
  • slicing์„ ์‚ฌ์šฉํ•˜์ง€ ์•Š๊ณ , ์ฒซ ๋จผ์งธ ๋ฌธ์ž์—ด์„ ๊ธฐ์ค€์œผ๋กœ ๋‘๊ณ  ๋น„๊ตํ•œ๋‹ค.
  • ์ด ํ•จ์ˆ˜๊ฐ€ ๋๋‚˜๋Š” ์‹œ์ ์€ ๊ฐ€์žฅ ์งง์€ ๊ธธ์ด์˜ ๋ฌธ์ž๊ฐ€ ''์ด ๋  ๋•Œ์ด๋ฏ€๋กœ, min_length ๋ณ€์ˆ˜๋ฅผ ์„ ์–ธํ•ด์„œ ์ด๋ฅผ ์ด์šฉํ•œ๋‹ค.
  • ''์ด ๋ฐœ์ƒํ•˜๋Š” ๊ฒฝ์šฐ๋Š” 2๊ฐ€์ง€, ์กฐ๊ฑด๋ฌธ์œผ๋กœ ์ฒ˜๋ฆฌํ•œ๋‹ค.
    • strs ์•ˆ์— ์žˆ๋Š” ์š”์†Œ๊ฐ€ ๋ชจ๋‘ ๊ณต๋ฐฑ์ด๋ฉด '' return
    • strs ์š”์†Œ ์ค‘ ํ•˜๋‚˜๋ผ๋„ ''์ด ์žˆ์œผ๋ฉด '' return

๊ทธ๋ž˜์„œ ์•„๋ž˜์™€ ๊ฐ™์ด ๋‹ค์‹œ ํ’€์ด.

def get_prefix(strs):
	result = ''
    min_length = min([len(str) for str in strs])
    
    if not strs : return result
    if min_length == 0 : return result
    i = 0 
    while True:
    	std_num = strs[0][i]
        for str in strs:
        	if str[i] != std_num : return result 
        result += std_num
        
        i += 1
        if min_length == i : return result 
profile
์˜ˆ๋น„ ๊ฐœ๋ฐœ์ž์˜ ๊ธฐ์ˆ  ๋ธ”๋กœ๊ทธ | explore, explore and explore

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