[CodeKata] Week1 - Day4,5

ใ…Žใ…Žยท2021๋…„ 6์›” 26์ผ
0

algorithm ํ’€์ด

๋ชฉ๋ก ๋ณด๊ธฐ
38/44
post-thumbnail
post-custom-banner

๐Ÿ“Œ CodeKata - Week1, Day4

๋ฌธ์ œ

์ˆซ์ž์ธ num์„ ์ธ์ž๋กœ ๋„˜๊ฒจ์ฃผ๋ฉด, ๋’ค์ง‘์€ ๋ชจ์–‘์ด num๊ณผ ๋˜‘๊ฐ™์€์ง€ ์—ฌ๋ถ€๋ฅผ ๋ฐ˜ํ™˜ํ•ด์ฃผ์„ธ์š”.

num: ์ˆซ์ž
return: true or false (๋’ค์ง‘์€ ๋ชจ์–‘์ด num์™€ ๋˜‘๊ฐ™์€์ง€ ์—ฌ๋ถ€)

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

num = 123
return false 
=> ๋’ค์ง‘์€ ๋ชจ์–‘์ด 321 ์ด๊ธฐ ๋•Œ๋ฌธ
num = 1221
return true 
=> ๋’ค์ง‘์€ ๋ชจ์–‘์ด 1221 ์ด๊ธฐ ๋•Œ๋ฌธ
num = -121
return false 
=> ๋’ค์ง‘์€ ๋ชจ์–‘์ด 121- ์ด๊ธฐ ๋•Œ๋ฌธ
num = 10
return false 
=> ๋’ค์ง‘์€ ๋ชจ์–‘์ด 01 ์ด๊ธฐ ๋•Œ๋ฌธ

ํ’€์ด1

def same_reverse(num):
    str_num = str(num)
    r_str_num = str_num [::-1] #๋’ค์—์„œ๋ถ€ํ„ฐ ์ถœ๋ ฅ
    if str_num == r_str_num:
        return True
    else:
        return False

ํ’€์ด2

def same_reverse(num):
    return str(num)[::-1] == str(num)

โžก๏ธ ๋ฌธ์ž์—ด์„ ๋’ค์—์„œ๋ถ€ํ„ฐ ์ถœ๋ ฅํ•ด์„œ ๊ธฐ์กด str๊ณผ ๊ฑฐ๊พธ๋กœ์ถœ๋ ฅํ•œ str์„ ๋น„๊ตํ–ˆ๋‹ค. ํ’€์ด2๋Š” ๊ทธ ์ฝ”๋“œ๋ฅผ ํ•œ์ค„๋กœ ๋งŒ๋“  ์ฝ”๋“œ์ด๋‹ค.

๐Ÿ“Œ CodeKata - Week1, Day5

๋ฌธ์ œ

strs์€ ๋‹จ์–ด๊ฐ€ ๋‹ด๊ธด ๋ฐฐ์—ด์ž…๋‹ˆ๋‹ค.

๊ณตํ†ต๋œ ์‹œ์ž‘ ๋‹จ์–ด(prefix)๋ฅผ ๋ฐ˜ํ™˜ํ•ด์ฃผ์„ธ์š”.

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

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

ํ’€์ด

def get_prefix(strs):
  if len(strs) == 0:
    return ''
  
  prefix = ''
  strs.sort()
  for i in range(len(strs[0])):
    if strs[0][i] == strs[-1][i]:
      prefix += strs[0][i]
    else:
      break
  return prefix

โžก๏ธ ๋งŒ์•ฝ ๋งจ ์ฒ˜์Œ ๋นˆ ๋ฌธ์ž์—ด์ด ๋“ค์–ด์˜ค๋ฉด ๋นˆ ๋ฌธ์ž์—ด์„ ๋ฆฌํ„ดํ•ด์ค€๋‹ค. ๊ทธ๋ฆฌ๊ณ  prefix๋ผ๋Š” ๋นˆ ๋ฌธ์ž์—ด์„ ๋งŒ๋“ ๋‹ค. ๊ทธ๋ฆฌ๊ณ  ๋ฆฌ์ŠคํŠธ๋ฅผ ์ •๋ ฌํ•ด์ค€๋‹ค. ๋งŒ์•ฝ ๋ฆฌ์ŠคํŠธ๋ฅผ ์ •๋ ฌํ•˜๋ฉด ๋ฆฌ์ŠคํŠธ์˜ ์•ˆ์˜ ๋ฌธ์ž์—ด๋“ค์€ ์•ŒํŒŒ๋ฒณ์ˆœ์œผ๋กœ ์ •๋ ฌ์ด ๋˜๋ฏ€๋กœ ๊ฐ€์šด๋ฐ๋Š” ๋น„๊ตํ•ด์ค„ ํ•„์š”๊ฐ€ ์—†๊ณ  ์ฒ˜์Œ๊ณผ ๋๋งŒ ๋น„๊ตํ•ด์ฃผ๋ฉด ๋œ๋‹ค. ๋”ฐ๋ผ์„œ for๋ฌธ์„ ๋Œ๋•Œ ์ฒซ๋ฒˆ์žฌ ๋ฌธ์ž์—ด์„ ๊ธฐ์ค€ ์ฒซ๋ฒˆ์งธ ๋ฌธ์ž์—ด๊ณผ ๋งˆ์ง€๋ง‰ ๋ฌธ์ž์—ด์˜ ๋ฐฐ์—ด์„ ํ•˜๋‚˜์”ฉ ๋น„๊ตํ•ด๊ฐ€๋ฉด์„œ ๊ฐ™์œผ๋ฉด prefix์— ์ถ”๊ฐ€ํ•ด์ฃผ๊ณ  ๊ทธ๋ ‡์ง€ ์•Š์œผ๋ฉด ๋ฉˆ์ถฐ์„œ prefix๋ฅผ ๋ฆฌํ„ดํ•œ๋‹ค.

post-custom-banner

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