Zak February 2016

Function output not printing?

trying to see whether the functions work, I tried printing out to see whether the random list could be sorted, however nothing seems to be printed. Also how would I measure the time it takes to sort the list out?

import random
import time
def mergeSort(mylist):
    if len(mylist) <= 1:
        return mylist
        mid = len(mylist) // 2
        left = mergeSort(mylist[:mid])
        right = mergeSort(mylist[mid:])
        return merge(left,right)


def merge(left,right):
    if not left:
        return right
    if not right:
        return left
    if left[0] < right[0]:
        return [left[0]]+merge(left[1:],right)
    else:
        return [right[0]]+merge(left,right[1:])
newList=[]
for i in range(100):
    newList.append(random.randint(1,1000))



val = mergeSort(newList)
print (val)

Nothing is outputted, why?

Answers


Prune February 2016

You blew your indentation. Here's the correct version:

def mergeSort(mylist):
    if len(mylist) <= 1:
        return mylist
    mid = len(mylist) // 2
    left = mergeSort(mylist[:mid])
    right = mergeSort(mylist[mid:])
    return merge(left,right)

In the version you posted, you have the main body of the routine still inside the if statement, but after the return. This means that it can never execute. If you look, you should find that your program di print something, the value None.

Post Status

Asked in February 2016
Viewed 2,075 times
Voted 9
Answered 1 times

Search




Leave an answer