# Python - need help to loop a list through functions using 4 different ranges (0-25, 0-100, 0-1000, 0-10000)

advertisements

Python Version - 3.3.2

I am writing a Python program that sets a list equal to a range of numbers (0-25), shuffles these numbers randomly and then sorts these numbers using four different sorting functions: bubble sort, selection sort, python sort, and insertion sort. There is also a timer function at the end of the program that times how long each function takes to sort the range of random numbers.

I need a way to change the range from (0-25) to (0-100) then (0-1000) and finally (0-10000). Each time it loops through a range of numbers and outputs how much time it takes to sort the list for each sorting function.

Here is an example of the code:

``````    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)
```
```

So again, my question is, how do I set the list equal to (0-25) loop through all of the sorting functions, output the time for each sorting function to complete, then change the list to equal (0-100), loop through all of the functions, output the time for each function and so on for (0-1000) and (0-100000)?

You want something like this:

``````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()
```
```