0

python

Create a function called middle_element that has one parameter named lst. If there are an odd number of elements in lst, the function should return the middle element. If there are an even number of elements, the function should return the average of the middle two elements. def middle_element(lst): if len(lst) % 2 == 0: sum = lst[int(len(lst)/2)] + lst[int(len(lst)/2) - 1] return sum / 2 else: return lst[int(len(lst)/2)] print(middle_element([5, 2, -10, -4, 4, 5])) Output : -7 1) why -1 ? --> sum = lst[int(len(lst)/2)] + lst[int(len(lst)/2) - 1]

2nd Jul 2022, 11:15 AM
Game0ver
Game0ver - avatar
3 Answers
+ 4
sum = lst[int(len(lst)/2)] + lst[int(len(lst)/2)-1] I'll try to explain the different parts of this line of code. First, the if condition checks if the length of list is even. Having even number of elements means that there is no middle element. Example: šŸ”ø [1, 2, 3, 4] That is why, the equation above is needed to solve for the 'mean' of the two middle numbers (in my example: 2 and 3) šŸ”¹ lst[int(len(lst)/2)] gets the right middle number. šŸ”ø [1, 2, 3, 4] šŸ”ø len(lst) ---> 4 šŸ”ø len(lst)/2 ---> 2 šŸ”ø lst[2] ---> 3 šŸ”¹ lst[int(len(lst)/2)-1] gets the left middle number. šŸ”ø [1, 2, 3, 4] šŸ”ø len(lst) ---> 4 šŸ”ø len(lst)/2 ---> 2 šŸ”ø (len(lst)/2)-1 ---> 1 šŸ”ø lst[1] ---> 2 These two middle numbers are added then divided into 2 to calculate their mean, or the actual middle number. Therefore, following my earlier example: >> lst[1] + lst[2] >> 2 + 3 >> 5 >> 5 / 2 # compute mean >> 2.5
2nd Jul 2022, 11:38 AM
noteve
noteve - avatar
+ 3
-1 because indexing starts at 0: A list of length 3 will have a max index of 2. noteve True. I also edited my reply as I had mis-read the question
2nd Jul 2022, 11:30 AM
Lisa
Lisa - avatar
+ 2
thank you so much . You are the best <3
2nd Jul 2022, 11:45 AM
Game0ver
Game0ver - avatar