2015-11-03 63 views
0

我很难用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]` 

我已经创建了两个例子,但我不知道如何开始的函数体。

回答

1

听起来就像是在这里需要一些索引符号:

>>> 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] 
+0

如果它是一个nonetype功能,是允许在体写成 '回归'? (对不起,我是一个新的程序员) – sarah

+0

@sarah我不确定你的意思是“NoneType”函数。 – TerryA

1

您可以使用元组交换成语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] 
0
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]