我很難用Python表達這一點。Python交換功能
這是需要做什麼的描述。
swap_cards:(INT的名單,INT) - > NoneType
swap_cards([3, 2, 1, 4, 5, 6, 0], 5) [3, 2, 1, 4, 5, 0, 6] swap_cards([3, 2, 1, 4, 5, 6, 0], 6) [0, 2, 1, 4, 5, 6, 3]`
我已經創建了兩個例子,但我不知道如何開始的函數體。
我很難用Python表達這一點。Python交換功能
這是需要做什麼的描述。
swap_cards:(INT的名單,INT) - > NoneType
swap_cards([3, 2, 1, 4, 5, 6, 0], 5) [3, 2, 1, 4, 5, 0, 6] swap_cards([3, 2, 1, 4, 5, 6, 0], 6) [0, 2, 1, 4, 5, 6, 3]`
我已經創建了兩個例子,但我不知道如何開始的函數體。
聽起來就像是在這裏需要一些索引符號:
>>> def swap_cards(L, n):
... if len(L) == n + 1:
... L[n], L[0] = L[0], L[n]
... return L
... L[n], L[n+1] = L[n+1], L[n]
... return L
...
>>> swap_cards([3, 2, 1, 4, 5, 6, 0], 5)
[3, 2, 1, 4, 5, 0, 6]
>>> swap_cards([3, 2, 1, 4, 5, 6, 0], 6)
[0, 2, 1, 4, 5, 6, 3]
您可以使用元組交換成語a, b = b, a
交換變量指出的是,對於邊緣的情況下,你需要環繞指數index % len(seq)
實施
def swap_cards(seq, index):
indexes = (index, (index + 1)% len(seq))
seq[indexes[0]], seq[indexes[1]] = seq[indexes[1]], seq[indexes[0]]
return seq
爲例Ë
>>> swap_cards([3, 2, 1, 4, 5, 6, 0], 6)
[0, 2, 1, 4, 5, 6, 3]
>>> swap_cards([3, 2, 1, 4, 5, 6, 0], 5)
[3, 2, 1, 4, 5, 0, 6]
def swap_cards(deck, index):
if index in range(0, len(deck)):
factor = (index + 1) % len(deck)
aux = deck[factor]
deck[factor] = deck[index]
deck[index] = aux
return deck
else:
return None
deck = [3, 2, 1, 4, 5, 6, 0]
new_deck = swap_cards(deck, 6)
print new_deck
輸出:
[0, 2, 1, 4, 5, 6, 3]
如果它是一個nonetype功能,是允許在體寫成 '迴歸'? (對不起,我是一個新的程序員) – sarah
@sarah我不確定你的意思是「NoneType」函數。 – TerryA