Python Swap Function

2019-03-04 06:46发布

问题:

I'm having a hard time expressing this in Python.

This is the description of what needs to be done.

swap_cards: (list of 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]`

I've created 2 examples, but I don't know how to start the body of the function.

回答1:

Sounds like some index notation is required here:

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


回答2:

You can use the tuple swap idiom a, b = b, ato swap the variable noting that for edge cases you need to wrap around the index index % len(seq)

Implementation

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

Example

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


回答3:

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

Output:

[0, 2, 1, 4, 5, 6, 3]


标签: python list swap