[python 기초] Code-kata week3-2

🖥 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.

좋은 웹페이지 즐겨찾기