0

Python 版本 - 3.3.2

我正在编写一个 Python 程序,它设置一个等于一系列数字(0-25)的列表,随机打乱这些数字,然后使用四种不同的排序函数对这些数字进行排序:冒泡排序、选择排序、python 排序和插入排序。程序末尾还有一个计时器功能,用于计时每个功能对随机数范围进行排序所需的时间。

我需要一种方法将范围从 (0-25) 更改为 (0-100),然后是 (0-1000),最后是 (0-10000)。每次它遍历一系列数字并输出为每个排序函数对列表进行排序所需的时间。

以下是代码示例:

    import random
    import time

    # Sets myList equal to a range with a range from 0-25
    myList = list(range(0,25))
    # Randomly shuffles the list of numbers between 0-25
    random.shuffle(myList)

    # Bubble Sort
    def bubbleSort(myList):
    ...(insert code)...

    # Selection Sort
    def selectionSort(myList):
    ...(insert code)...

    # Python Sort
    def pythonSort(myList):
    ...(insert code)...

    # Insertion Sort
    def insertionSort(myList):
    ...(insert code)...

    # Timer
    def timer(array, func):
    ...(insert code)...
    print("Time needed for", func.__name__, 'to sort',len(array),'items: ',diff)

    timer(myList, selectionSort)
    timer(myList, bubbleSort)
    timer(myList, pythonSort)
    timer(myList, insertionSort)

所以再次,我的问题是,我如何设置列表等于(0-25)循环遍历所有排序函数,输出每个排序函数完成的时间,然后将列表更改为等于(0-100),循环遍历所有函数,输出每个函数的时间等等(0-1000)和(0-100000)?

4

3 回答 3

2

正如 wjl 建议的那样

for length in [25, 100, 1000, 10000]:
    myList = range(length) # range(25) is equal to range(0,25)

    timer(myList, selectionSort) #assuming that selectionSort doesn't alter myList
    timer(myList, bubbleSort)
    timer(myList, pythonSort)
    timer(myList, insertionSort)
于 2013-09-10T01:16:50.963 回答
0

你想要这样的东西:

from datetime import datetime
from random import shuffle


def timer(data, sortfn):
    start = datetime.now()
    sortfn(data)
    end = datetime.now()
    return end - start

def tester():
    lengths = (25, 100, 1000, 10000)
    sortfns = (selectionSort, bubbleSort, pythonSort, insertionSort)
    for length in lengths:
        myList = list(range(length))
        shuffle(myList)
        for sortfn in sortfns:
            # Take a deep copy of the shuffled data
            shuffled = myList[:]
            # Sort the shuffled data
            elapsed = timer(shuffled, sortfn)
            print("{0}({1}): {2}".format(sortfn.__name__, length, elapsed))

tester()
于 2013-09-10T23:12:28.700 回答
0

你可以把你的参数放在一个元组列表中,然后扩展元组:

>>> ranges=[(0,10),(15,20),(200,210,2)]   # correspond to start, stop, step in range
>>> for r in ranges:
...    for i in range(*r):
...       # do whatever...

或者:

>>> ranges=[(0,10),(15,20),(200,210,2)]   # correspond to start, stop, step in range
>>> for r in ranges:
...    your_list=list(range(*r))
...    # do whatever...
于 2013-09-10T01:31:58.013 回答