Python 3需要帮助

时间:2016-03-22 15:25:12

标签: python-3.x

def bubble_down(L, start, end):
    """ (list, int, int) -> NoneType

    Bubble down through L from indexes end through start, swapping items that are out of place.

    >>> L = [4, 3, 2, 1, 0]
    >>> bubble_down(L, 1, 3)
    >>> L
    [4, 1, 3, 2, 0]
    """
    for i in range(start, end):
        if L[i] < L[i]:
            L[i - 1], L[i] = L[i], L [i - 1]

这个功能不会....我不明白为什么docstring示例L返回[4,1,3,2,0],而不是[4,1,2,3, 0]

2 个答案:

答案 0 :(得分:0)

你几乎就在那里。你的比较是错误的(你正在比较相同的元素),你可能想要更多地考虑你的结束债券。 最重要的是,您希望迭代该过程,直到没有变化。

这是一个正确的版本:

def  bubble_down(to_sort, start=0, end=None):
    if end is None:
        end  = len(to_sort)
    did_change = True
    while did_change:
        did_change = False
        for i in range(start, end-1):
            if to_sort[i] > to_sort[i+1]:
                did_change = True
                to_sort[i], to_sort[i+1] = to_sort[i+1], to_sort[i]

    return to_sort


>>> print(bubble_down([5, 7, 6 , 1]))
[1, 5, 6, 7]
>>> print bubble_down([4, 3, 2, 1, 0])
[0, 1, 2, 3, 4]

答案 1 :(得分:-2)

您只需要在解决方案中包括该步骤

def bubble_down(L, start, end):
    """ (list, int, int) -> NoneType

    Bubble down through L from indexes end through start, swapping items that are out of place.

    >>> L = [4, 3, 2, 1, 0]
    >>> bubble_down(L, 1, 3)
    >>> L
    [4, 1, 3, 2, 0]
    """
    for i in range(start, end, -1):
        if L[i] < L[i]:
            L[i - 1], L[i] = L[i], L [i - 1]