[python ๊ธฐ์ดˆ] Code-kata week2-3

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

[wecode] Code-kata

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

๐Ÿ–ฅ Code-kata week2-3


๋ฌธ์ œ
s๋Š” ์—ฌ๋Ÿฌ ๊ด„ํ˜ธ๋“ค๋กœ ์ด๋ฃจ์–ด์ง„ String ์ธ์ž์ž…๋‹ˆ๋‹ค. s๊ฐ€ ์œ ํšจํ•œ ํ‘œํ˜„์ธ์ง€ ์•„๋‹Œ์ง€ true/false๋กœ ๋ฐ˜ํ™˜ํ•ด์ฃผ์„ธ์š”.

์ข…๋ฅ˜๋Š” '(', ')', '[', ']', '{', '}' ์œผ๋กœ ์ด 6๊ฐœ ์žˆ์Šต๋‹ˆ๋‹ค. ์•„๋ž˜์˜ ๊ฒฝ์šฐ ์œ ํšจํ•ฉ๋‹ˆ๋‹ค.

ํ•œ ๋ฒˆ ๊ด„ํ˜ธ๋ฅผ ์‹œ์ž‘ํ–ˆ์œผ๋ฉด, ๊ฐ™์€ ๊ด„ํ˜ธ๋กœ ๋๋‚ด์•ผ ํ•œ๋‹ค. ๊ด„ํ˜ธ ์ˆœ์„œ๊ฐ€ ๋งž์•„์•ผ ํ•œ๋‹ค. ์˜ˆ๋ฅผ ๋“ค์–ด ์•„๋ž˜์™€ ๊ฐ™์Šต๋‹ˆ๋‹ค.

s = "()"
return true

s = "()[]{}"
return true

s = "(]"
return false

s = "([)]"
return false

s = "{[]}"
return true


ํ’€์ด

์ผ๋‹จ ์กฐ๊ฑด์— ๋งž์œผ๋ ค๋ฉด, ๋ฌด์กฐ๊ฑด ํ•œ ์Œ์˜ ๊ด„ํ˜ธ๋Š” ๋ฐ”๋กœ ์–‘์˜†์— ๋ถ™์–ด์žˆ์–ด์•ผ ํ•˜๊ณ , ๋ณต์ˆ˜์˜ ๊ฐœ์ˆ˜๊ฐ€ ์žˆ์œผ๋ฏ€๋กœ ๋‹ค ๊ฑธ๋Ÿฌ๋‚ด์•ผ ํ•œ๋‹ค.
๊ทธ๋ž˜์„œ ๊ด„ํ˜ธ ๊ฐ 6๊ฐœ๋ฅผ 3๊ฐœ ์Œ์œผ๋กœ ๋งŒ๋“ค์–ด์„œ list๋กœ ๋ฌถ๊ณ , ์ด list์˜ ๊ฐ’์„ for๋ฌธ์œผ๋กœ ๋Œ๋ฆฌ๋Š” ๋ฐฉ๋ฒ•์„ ์‚ฌ์šฉํ–ˆ๋‹ค.

  • ๊ด„ํ˜ธ list๋ฅผ ๋งŒ๋“ ๋‹ค : lst = ["()","[]","{}"]
  • ํ•ด๋‹น ๊ด„ํ˜ธ๊ฐ€ ๋ฐœ๊ฒฌ๋˜๋ฉด replace๋กœ ๊ณต๋ฐฑํ™” > ํ•ด๋‹น ๊ด„ํ˜ธ๊ฐ€ ์—†์„ ๋•Œ๊นŒ์ง€ ๋ฐ˜๋ณต
def is_valid(string):
    lst = ["()","[]","{}"]
    for i in range(len(string)):
      for l in lst:
        while l in string:
          string = string.replace(l,'')

    if string == "": return True
    return False

์ถ”๊ฐ€ point: del๊ณผ remove

  • del : ์˜ˆ์•ฝ์–ด, index๊ฐ’์œผ๋กœ ์‚ญ์ œ (์˜ˆ์‹œ: del string[1])
  • remove : ๊ฐ’์œผ๋กœ ์‚ญ์ œ (์˜ˆ์‹œ: string.remove('[]'))
profile
์˜ˆ๋น„ ๊ฐœ๋ฐœ์ž์˜ ๊ธฐ์ˆ  ๋ธ”๋กœ๊ทธ | explore, explore and explore

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