数字のリストが与えられ、そのうちの 1 つを次の 2 つの数字と交換したい場合。最初の数字を 2 回交換せずに、これを 1 回で行う方法はありますか?
より具体的には、次の swap 関数があるとします。
def swap_number(list, index):
'''Swap a number at the given index with the number that follows it.
Precondition: the position of the number being asked to swap cannot be the last
or the second last'''
if index != ((len(list) - 2) and (len(list) - 1)):
temp = list[index]
list[index] = list[index+1]
list[index+1] = temp
さて、この関数を使用して、番号に対して swap を 2 回呼び出さずに、番号を次の 2 つの番号と交換するにはどうすればよいでしょうか。
例: 次のリストがあります。list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
では、3 を 4 と 5 と一発で入れ替えるにはどうすればよいでしょうか。
期待される出力は
リスト = [0, 1, 2, 4, 5, 3, 6, 7, 8, 9]