I am trying to write a function called "k_largest(input,output)" which takes two Python lists of numbers and then fills the output list with the largest numbers of the input list in ascending order, depending on the size of the output list.
The test is:
input = [50, 30, 60, 10, 0, 40]
output = [0, 0, 0]
k_largest(input,output)
print(output)
Answer:
[40, 50, 60]
This is my code: (The merge_sort function is just used to sort the input list into descending order.)
def k_largest(input, output):
merge_sort(input)
input = input[:len(output)]
input = input[::-1]
output = list(input)
print (output)
def merge_sort(list):
count = 0
for index in range(1, len(list)):
value = list[index]
i = index - 1
while i >= 0:
if value > list[i]:
list[i+1] = list[i]
list[i] = value
i = i - 1
count = count + 1
else:
break
For some reason my code is just outputting the original output list instead of the new output list.
For example:
[0, 0, 0]
Instead of:
[40, 50, 60]
I'm pretty sure there's a more effective way of doing this as well.