Python 索引器:快速排序算法中的列表索引超出范围

Python 索引器:快速排序算法中的列表索引超出范围,python,algorithm,quicksort,index-error,Python,Algorithm,Quicksort,Index Error,我正在尝试编写一个“快速排序”算法的python脚本 这是我的代码: def quick_sort(sequence): pivot = sequence.pop() greater =[] lower = [] for i in sequence: if sequence[i] > pivot : greater.append(sequence[i]) else:

我正在尝试编写一个“快速排序”算法的python脚本

这是我的代码:

def quick_sort(sequence):
    pivot = sequence.pop()
    greater =[]
    lower = []

    for i in sequence:
            if sequence[i] > pivot : 
                greater.append(sequence[i])
            else:
                lower.append(sequence[i])
    return lower + pivot + greater 

sequence = [1,6,3,5,9,6,0,9,3,5,12,37,33,65,55,454,45,len("good")]
quick_sort(sequence)
但我有一个错误:

Traceback (most recent call last):
  File "<string>", line 14, in <module>
  File "<string>", line 7, in quick_sort
IndexError: list index out of range
回溯(最近一次呼叫最后一次):
文件“”,第14行,在
文件“”,第7行,快速排序
索引器:列表索引超出范围

有人能帮我纠正这个错误吗?

根据评论,这个问题只想对列表进行排序。这很简单。要么这样做:

lst = sorted(lst)
或者,如果不想使用equal运算符:

lst.sort()

将自动排序。

问题在于这两行:

        for i in sequence:
            if sequence[i] > pivot : 
在Python中,列表中x的
将迭代
\u列表
的值,而不是索引。在您的示例中,这意味着在某个点上,
i==37
if
条件尝试访问超出范围的
序列[37]
。有两种方法可以解决此问题:

  • 对于范围内的i(len(序列)):
    将为您提供索引
  • 只需使用
    i
    的值,而不是将其用作索引(也在附加的行中)。就我个人而言,这将是我的偏好——总体而言,我觉得它更整洁

  • 另外,请注意
    lower
    greater
    是列表,而
    pivot
    是一个整数,因此不能执行
    lower+pivot+greater
    -您必须首先将
    pivot
    包装到列表中(
    lower+[pivot]+greater
    )。

    这是我不久前实现的快速排序,可以帮助您设计和测试自己的快速排序算法:

    import random
    from typing import TypeVar, List
    from scipy import stats
    
    T = TypeVar('T')
    
    
    def quick_sort(input_list: List[T]) -> List[T]:
        """"
        Returns an ascending sorted list;
        Input variable is an integer or float array;
        Theoretical Complexity: O(N*Log N) Time and O(N) Memory
        """
    
        sort(input_list, 0, len(input_list) - 1)
        return input_list
    
    
    def sort(input_list: List[T], start_index: int, end_index: int) -> None:
        """Recursively sorts the two pivot-divided sublists;"""
        if start_index >= end_index:
            return
        pivot_index = partition(input_list, start_index, end_index)
        sort(input_list, start_index, pivot_index - 1)
        sort(input_list, pivot_index + 1, end_index)
    
    
    def partition(input_list: List[T], start_index: int, end_index: int) -> int:
        """
        Returns the end index; Partitions a list into two sublists;
        """
        pivot = input_list[start_index]
    
        i, j = start_index + 1, end_index
    
        while i <= j:
            while input_list[i] < pivot and i < end_index:
                i += 1
            while input_list[j] > pivot:
                j -= 1
    
            if i < j:
                temp = input_list[i]
                input_list[i] = input_list[j]
                input_list[j] = temp
                i += 1
                j -= 1
            else:
                break
    
        input_list[start_index] = input_list[j]
        input_list[j] = pivot
    
        return j
    
    
    if __name__ == "__main__":
    
        # Creates a dash line string and a new line for in between the tests.
        delimiter = "-" * 70 + "\n"
    
        # Generates a random integer list.
        test_list_integer = random.sample(range(-100, 100), 15) * 3
        print(f"""The unsorted integer array is:
            {test_list_integer}""")
        print(delimiter)
    
        # Generates a random float list.
        test_list_float = stats.uniform(0, 100).rvs(45)
        print(f"""The unsorted float array is:
            {test_list_float}""")
        print(delimiter)
    
        # Sample float/integer test list for input.
        integer_float_input = list(test_list_integer + test_list_float)
    
        # Sample float/integer test list for output.
        integer_float_output = sorted(integer_float_input)
    
        sorting_algorithms = [
            ("Quick Sort", quick_sort)
        ]
    
        # Testing
        for description, func in sorting_algorithms:
            if (func(integer_float_input.copy()) == integer_float_output):
                print(f"{description} Test was Successful.")
            else:
                print(f"{description} Test was not Successful.")
            print(f"""{description} (Integer):
                {func(test_list_integer.copy())}""")
            print(f"""{description} (Float):
                {func(test_list_float.copy())}""")
            print(delimiter)
    
    
    参考


    这是一个很好的例子。

    我只想说:
    排序(序列)
    就是你所需要的
    ,因为我在序列中:
    已经在迭代列表的内容,而不是它们的索引。这是一个项目,还是你只是想对列表排序?@AnnZen不,我只是想对列表排序。但是!我是初学者!我想使用快速排序的概念,
    The unsorted integer array is:
            [-37, 74, -9, 58, 96, 82, 32, 94, -77, -54, -13, -10, -82, 57, 6, -37, 74, -9, 58, 96, 82, 32, 94, -77, -54, -13, -10, -82, 57, 6, -37, 74, -9, 58, 96, 82, 32, 94, -77, -54, -13, -10, -82, 57, 6]
    ----------------------------------------------------------------------
    
    The unsorted float array is:
            [ 4.46747765 21.96382498 21.00086463 49.15870339 95.19971828 94.5108942
      1.88156027 49.1355604  78.5032007  32.4662292  15.0415828  75.04492651
     29.491373    4.02412264 22.34068707 97.39317437 27.64026964 85.52244153
      0.53119133 16.63664738 86.79522363 33.07979585 88.50108333 57.40225507
     72.25826399 99.82793291 99.84493522 15.96858729 33.58735178  1.70611819
     68.07308792 46.09522364 21.42563941  5.55154387 10.60707898 92.78939519
     77.01866529 14.12783987 87.17625745 52.8310454  19.39884535 94.30883322
     96.14062517 45.56022192 24.39705178]
    ----------------------------------------------------------------------
    
    Quick Sort Test was Successful.
    Quick Sort (Integer):
                [-82, -82, -82, -77, -77, -77, -54, -54, -54, -37, -37, -37, -13, -13, -13, -10, -10, -10, -9, -9, -9, 6, 6, 6, 32, 32, 32, 57, 57, 57, 58, 58, 58, 74, 74, 74, 82, 82, 82, 94, 94, 94, 96, 96, 96]
    Quick Sort (Float):
                [ 0.53119133  1.70611819  1.88156027  4.02412264  4.46747765  5.55154387
     10.60707898 14.12783987 15.0415828  15.96858729 16.63664738 19.39884535
     21.00086463 21.42563941 21.96382498 22.34068707 24.39705178 27.64026964
     29.491373   32.4662292  33.07979585 33.58735178 45.56022192 46.09522364
     49.1355604  49.15870339 52.8310454  57.40225507 68.07308792 72.25826399
     75.04492651 77.01866529 78.5032007  85.52244153 86.79522363 87.17625745
     88.50108333 92.78939519 94.30883322 94.5108942  95.19971828 96.14062517
     97.39317437 99.82793291 99.84493522]
    ----------------------------------------------------------------------