Ask your own question, for FREE!
Computer Science 16 Online
OpenStudy (anonymous):

Help with python. Question below:

OpenStudy (anonymous):

def merge_sort(L): def merge(left, right): i, j = 0, 0 ans = [] while i<len(left) and j<len(right): if left[i] <= right[j]: ans.append(left[i]) i += 1 elif left[i] >= right[j]: ans.append(right[j]) j += 1 while i<len(left): ans.append(left[i]) i += 1 while j<len(right): ans.append(right[j]) j += 1 return ans def divide(L): if len(L)<2: return L[:] else: mid=len(L)/2 left = divide(L[:mid]) right = divide(L[mid:]) return merge(left, right) divide(L) l= [1,5,2,6,9,0] print merge_sort(l) I am unable to find where I went wrong.

OpenStudy (anonymous):

Your `merge_sort()` function doesn't return anything. It should `return divide(L)` instead of just `devide(L)` You can also simplify that a little. This: ```python while i<len(left): ans.append(left[i]) i += 1 ``` Is equivalent to: ``` ans += left[i:] ``` And the same for `right`. Also the condition of `elif left[i] >= right[j]:` is redundant, because if you got there then it means `right[j] > left[i]` so you can replace that with a simple `else:` Besides that it works fine to me, good job \( \Large ☺ \)

OpenStudy (anonymous):

Oh! Alright! I've been trying to code this since the the past two days. And when it's finally working, I feel accomplished :) Thank you! :)

Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!
Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!