[pythonベース]Code-kata週3-2


🖥 Code-kata week3-2
質問する
文字で構成された配列をinputで伝える場合は、文字を逆に戻してください.
新しいシナリオは宣言できません.
受信したパラメータ配列を変更してください.
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"]
に答える
全く逆の問題.
逆スライスを適用すればよい.
def reverse_string(s):
  return s[::-1]
スライスする場合、各位置の値はstart、end、stepです.
したがって,上記のように記入すると,(-1)をsのstart-endに逆順にすることを意味する.
では、reverse()list[::-1]のどちらがより良い方法なのでしょうか.詳細な例はここをクリックです.
要するに、
スライスは新しいlistを作成するのと同じです.
インバース操作は、既存のリストの要素をインバース操作します.
スピードの面では、逆さにしたほうがいいです.reverseは逆シーケンスにすぎず、新しいlistは返されません.
  • 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.