Help needed in this code. Explain me the code. | Sololearn: Learn to code for FREE!
Novo curso! Todo programador deveria aprender IA generativa!
Experimente uma aula grƔtis
0

Help needed in this code. Explain me the code.

def merge(L): if len(L) <= 1: return L mid = len(L)//2 r = merge(L[:mid]) l = merge(L[mid:]) print(r) print(l) li = (3, 4, 5, 6, 67, 23, 46, 76) merge(li) Out: [3] [4] [5] [6] None None [67] [23] [46] [76] None None None None

15th Sep 2020, 8:26 PM
Shafayet Arish
Shafayet Arish - avatar
2 Respostas
0
Passing li to function If len of list is <=1 then return list Else find mid element Then again call function with list elements from 0 to mid as passing list this recursively pass list until only one element.. It is dividing list in merge sort implementation. But actually missing merging, and sorting implementation. Take a look at https://www.sololearn.com/learn/660/?ref=app For more, run this code and see : def merge(L): if len(L) <= 1: return L mid = len(L)//2 print(L) print("mid element at index=",mid) r = merge(L[:mid]) #right list recursion l = merge(L[mid:]) #left list recursion print("right =",r) print("left =",l) li = (3, 4, 5, 6, 67, 23, 46, 76) merge(li)
15th Sep 2020, 10:56 PM
Jayakrishna šŸ‡®šŸ‡³
0
I hope am able to explain this stuff as clearly as possible. When you assign r and l to the recursive function, it runs for each single value but when the recursion returns, it is assigned to r and l. That is something like r = merge(L[:4]) runs for each recursion but does not store any value in r when the recursion comes back and so prints none. To fix this simply comment or remove your two print function and remove the assignment in each of the merge so that you just have : merge(L[:mid]) merge(L[mid:]) And finally change your return L to print(L) and you are good to go. Debugging this your code really scratched a part of my brain
15th Sep 2020, 11:28 PM
Zelus
Zelus - avatar