I’ve read all 3 topics linked to this exercise, and researched more on floor division to try to fully understand the concept of your solution:
if n % 2:
return float(lst[m - 1] + lst[m]) / 2
It is very concise and it will help me greatly if you could clarify this section:
if n % 2:
This is an example I did for myself to understand better:
a = len(lst)
b = a // 2
if b % 2:
return (lst[b] + lst[b-1]) / 2
I know for odd elements, b % 2 = 1 and for even elements, b % 2 = 0.
As the function just writes if b % 2: instead of if b % 2 == 1: or if b % 2 == 0, I want to confirm if this is left as such as default since the floor division (// 2) is already done, so the outcome of if b % 2: is limited to 2 absolute answers.
This will make sense for the subsequent return line on the same indent level as if b % 2.
In my example below, the answer printed -7.0, which is strange.
a = len(lst) #6 elements
b = a // 2 #6//2 = 3
if b % 2 == 0: #if 3 % 2 = 1 == 0:
return lst[b] #return lst = -4
return (lst[b] + lst[b-1]) / 2 # return -4 + -10 / 2 = -7.0
print(middle_element([5, 2, -10, -4, 4, 5]))
I have been staring at these for hours, maybe I need to look at it again.
I hope you can shed some light on this, I appreciate your contributions!