在递归调用python中交换列表元素

时间:2017-05-23 12:54:12

标签: python recursion swap

我想在列表中创建简单的函数交换随机元素。 但它在递归调用中不起作用。

在第一次递归调用,元素交换工作中, 但嵌套的递归调用(或第一次递归调用中的嵌套递归调用)并不起作用。

我不知道为什么只交换第一次递归调用。

下面是结果。

谢谢大家。

def change(lst):
    if len(lst)>4:
        a, b = np.random.randint(0, len(lst)), np.random.randint(0, len(lst))
        print(lst)
        lst[a], lst[b] = lst[b], lst[a]
        print(lst)
        mid = int(len(lst)/2)
        change(lst[:mid])
        change(lst[mid:])
k = list(range(0, 20))
change(k)
print(k)

`

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
[0, 19, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 1]
[0, 19, 2, 3, 4, 5, 6, 7, 8, 9]
[3, 19, 2, 0, 4, 5, 6, 7, 8, 9]
[3, 19, 2, 0, 4]
[3, 0, 2, 19, 4]
[5, 6, 7, 8, 9]
[5, 6, 8, 7, 9]
[10, 11, 12, 13, 14, 15, 16, 17, 18, 1]
[10, 11, 12, 13, 14, 15, 16, 17, 18, 1]
[10, 11, 12, 13, 14]
[10, 14, 12, 13, 11]
[15, 16, 17, 18, 1]
[15, 16, 17, 18, 1]
[0, 19, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 1] <= result. 

2 个答案:

答案 0 :(得分:0)

这是因为您lst[:mid]lst[mid:]创建了原始列表的副本。解决方案是将change()相同的列表和(单独)传递给要处理的范围。

答案 1 :(得分:0)

问题在于你的递归调用:

change(lst[:mid])
change(lst[mid:])

您使用切片运算符。切片运算符会构建新列表,因此您的更改会在新列表中进行,并且不会反映在原始列表中(因为它是副本)。

你可以做的是改用指数:

def change(lst,frm=0,to=None):
    if to is None: # set the default to the end of the list
        to = len(lst)
    if to-frm > 4:
        a, b = np.random.randint(frm,to), np.random.randint(frm,to)
        print(lst)
        lst[a], lst[b] = lst[b], lst[a]
        print(lst)
        mid = (frm+to)//2
        change(lst,frm,mid)
        change(lst,mid,to)

然后我们获得:

>>> k = list(range(0, 20))
>>> change(k)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
[0, 1, 2, 3, 4, 12, 6, 7, 8, 9, 10, 11, 5, 13, 14, 15, 16, 17, 18, 19]
[0, 1, 2, 3, 4, 12, 6, 7, 8, 9, 10, 11, 5, 13, 14, 15, 16, 17, 18, 19]
[0, 1, 2, 3, 4, 12, 6, 7, 8, 9, 10, 11, 5, 13, 14, 15, 16, 17, 18, 19]
[0, 1, 2, 3, 4, 12, 6, 7, 8, 9, 10, 11, 5, 13, 14, 15, 16, 17, 18, 19]
[0, 1, 4, 3, 2, 12, 6, 7, 8, 9, 10, 11, 5, 13, 14, 15, 16, 17, 18, 19]
[0, 1, 4, 3, 2, 12, 6, 7, 8, 9, 10, 11, 5, 13, 14, 15, 16, 17, 18, 19]
[0, 1, 4, 3, 2, 7, 6, 12, 8, 9, 10, 11, 5, 13, 14, 15, 16, 17, 18, 19]
[0, 1, 4, 3, 2, 7, 6, 12, 8, 9, 10, 11, 5, 13, 14, 15, 16, 17, 18, 19]
[0, 1, 4, 3, 2, 7, 6, 12, 8, 9, 10, 11, 5, 13, 14, 15, 16, 17, 18, 19]
[0, 1, 4, 3, 2, 7, 6, 12, 8, 9, 10, 11, 5, 13, 14, 15, 16, 17, 18, 19]
[0, 1, 4, 3, 2, 7, 6, 12, 8, 9, 5, 11, 10, 13, 14, 15, 16, 17, 18, 19]
[0, 1, 4, 3, 2, 7, 6, 12, 8, 9, 5, 11, 10, 13, 14, 15, 16, 17, 18, 19]
[0, 1, 4, 3, 2, 7, 6, 12, 8, 9, 5, 11, 10, 13, 14, 15, 16, 17, 18, 19]
>>> print(k)
[0, 1, 4, 3, 2, 7, 6, 12, 8, 9, 5, 11, 10, 13, 14, 15, 16, 17, 18, 19]