I have my code which does a quick sort on a list of values:
def Quick_sort_random(random_list):
r = random_list.copy()
def inner(r):
if len(r) < 2:
return r
p = random.randint(0, len(r) - 1)
pivot = r[p]
left = list(filter(lambda x: x <= pivot, r[:p] r[p 1:]))
right = list(filter(lambda x: x > pivot, r[:p] r[p 1:]))
return Quick_sort_random(left) [pivot] Quick_sort_random(right)
a = inner(r)
return random_list,a
This throws the error:
TypeError: can only concatenate tuple (not "list") to tuple
I have the inner() function because I want to return both the original list and the sorted list. How can I fix this?
CodePudding user response:
Your Quick_sort_random
function returns a tuple but you only need the second item in it for the sorting. Change the last line in inner
to:
return Quick_sort_random(left)[1] [pivot] Quick_sort_random(right)[1]
CodePudding user response:
Just return the sorted list in inner
function:
import random
def Quick_sort_random(random_list):
r = random_list.copy()
def inner(r):
if len(r) < 2:
return r
p = random.randint(0, len(r) - 1)
pivot = r[p]
left = list(filter(lambda x: x <= pivot, r[:p] r[p 1:]))
right = list(filter(lambda x: x > pivot, r[:p] r[p 1:]))
unsorted_left, sorted_left = Quick_sort_random(left)
unsorted_right, sorted_right = Quick_sort_random(right)
return sorted_left [pivot] sorted_right
a = inner(r)
return random_list,a
print(Quick_sort_random([4,5,1,5,2,3]))
Output:
([4, 5, 1, 5, 2, 3], [1, 2, 3, 4, 5, 5])