Exercise 5, “Middle Item”
My question is about the difference between my code and the solution code.
if len(lst) % 2 == 0: # this means it's even halflength = int(len(lst) / 2) return (lst[halflength] + lst[halflength + 1]) / 2 else: #it'll be odd oddhalf = (len(lst) / 2) + .5 return oddhalf
This code works perfectly when I call the function with [1, 2, 3, 4] or [1, 2, 3, 4, 5]. However, when I try the list provided in the exercise for debugging, [5, 2, -10, -4, 4, 5], my code returns
0.0. Why? It doesn’t make any sense, I can’t see any reason whatsoever why the code I have wouldn’t be able to accommodate negative numbers or numbers out-of-sequence. I’m pretty much only interacting with the indexes, not even the values themselves. I can’t even figure out if the problem is the list being out-of-sequence or the fact it contains negative integers.
Also, the solution code has something I don’t understand:
lst[int(len(lst)/2)] + lst[int(len(lst)/2) - 1]
It converts a len() item into an int inside the square brackets that are supposed to reference an index. Why? And how is that different from mine?
For debugging, I have a version that prints rather than returns in PyCharm.
def middle_element(lst): if len(lst) % 2 == 0: # this means it's even halflength = int(len(lst) / 2) print((lst[halflength] + lst[halflength + 1]) / 2) else: #it'll be odd oddhalf = (len(lst) / 2) + .5 print(oddhalf)) middle_element([1,3,2,4]) # should be 2.5 but yields 3.0 middle_element([5,4,3,2,1]) # correctly yields 3.0 middle_element([1,-2,3,-4,5]) # correctly yields 3.0 middle_element([-1, -2, -3, -4]) # should yield -2.5 but yields -3.5 middle_element([5, 2, -10, -4, 4, 5]) # should yield -7.0 but yields 0.0
This has only deepened the mystery.
Aside: There has been an enormous, sudden jump in difficulty. I am pulling my hair out over these last two exercises and don’t fully understand them even with the solutions right in front of me. I’m going back and reviewing my notes, I’m Googling official documentation (which is almost absolutely inaccessible at my level), and watching YouTube videos. I even installed an interpreter on my device to debug code outside of the CodeCademy environment.
I can’t figure out why these were so difficult for me or why my notes helped me so little.