[python ๊ธฐ์ดˆ] Code-kata week3-2

EMMAยท2022๋…„ 4์›” 5์ผ
0

[wecode] Code-kata

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

๐Ÿ–ฅ Code-kata week3-2


๋ฌธ์ œ
๋ฌธ์ž๋กœ ๊ตฌ์„ฑ๋œ ๋ฐฐ์—ด์„ input์œผ๋กœ ์ „๋‹ฌํ•˜๋ฉด, ๋ฌธ์ž๋ฅผ ๋’ค์ง‘์–ด์„œ return ํ•ด์ฃผ์„ธ์š”.

์ƒˆ๋กœ์šด ๋ฐฐ์—ด์„ ์„ ์–ธํ•˜๋ฉด ์•ˆ ๋ฉ๋‹ˆ๋‹ค.
์ธ์ž๋กœ ๋ฐ›์€ ๋ฐฐ์—ด์„ ์ˆ˜์ •ํ•ด์„œ ๋งŒ๋“ค์–ด์ฃผ์„ธ์š”.
Input: ["h","e","l","l","o"]
Output: ["o","l","l","e","h"]

Input: ["H","a","n","n","a","h"]
Output: ["h","a","n","n","a","H"]


ํ’€์ด

๊ทธ๋Œ€๋กœ reverse ํ•˜๋Š” ๋ฌธ์ œ.
์—ญ์ˆœํ•ด์ฃผ๋Š” slicing์„ ์ ์šฉํ•˜๋ฉด ๋œ๋‹ค.

def reverse_string(s):
  return s[::-1]

slicingํ•  ๋•Œ ๊ฐ ์œ„์น˜์˜ ๊ฐ’์€ start,end,step์ด๋‹ค.
๊ทธ๋ž˜์„œ ์œ„์™€ ๊ฐ™์ด ์ž‘์„ฑํ•˜๋ฉด s์˜ start-end๊นŒ์ง€ ์—ญ์ˆœ(-1)ํ•˜๊ฒ ๋‹ค๋Š” ์˜๋ฏธ๋‹ค.

๊ทธ๋ ‡๋‹ค๋ฉด reverse() ์™€ list[::-1] ์ค‘ ๋ฌด์—‡์ด ๋” ์ข‹์€ ๋ฐฉ๋ฒ•์ผ๊นŒ. ์ž์„ธํ•œ ์˜ˆ์‹œ๋Š” ์—ฌ๊ธฐ ํด๋ฆญ.

์š”์•ฝํ•˜์ž๋ฉด,
slicing์€ ์•„์˜ˆ ์ƒˆ๋กœ์šด list๋ฅผ ๋งŒ๋“ค์–ด๋‚ด๋Š” ๊ฒƒ๊ณผ ๊ฐ™๊ณ ,
reverseํ•˜๋Š” ๊ฒƒ์€ ๊ธฐ์กด list์˜ ์š”์†Œ๋“ค์„ ์—ญ์ˆœ์‹œ์ผœ์ฃผ๋Š” ๊ฒƒ์ด๊ธฐ ๋•Œ๋ฌธ์—
reverse๊ฐ€ ์†๋„ ์ธก๋ฉด์—์„  ๋” ๋‚ซ๋‹ค๊ณ  ํ•œ๋‹ค. reverse๋Š” ์—ญ์ˆœ๋งŒ ํ•  ๋ฟ ์ƒˆ๋กœ์šด list๋ฅผ return ํ•ด์ฃผ์ง€ ์•Š๋Š”๋‹ค.

  • slicing: "it iterates the entire list counting from the last element to the first element resulting in a reversed list"
  • reverse: The built-in reversed() function in Python returns an iterator object rather than an entire list. If there is a need to store the reverse copy of data then slicing can be used but if one only wants to iterate the list in reverse manner, reversed() is definitely the better option.
profile
์˜ˆ๋น„ ๊ฐœ๋ฐœ์ž์˜ ๊ธฐ์ˆ  ๋ธ”๋กœ๊ทธ | explore, explore and explore

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