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]

15th Apr 2022, 4:46 PM
Game0ver
Game0ver - avatar
2 Answers
+ 1
Because list index starts from 0. int(len(lst)/2) returns 3 You need sum of values at indexes 2,3 for even length..
15th Apr 2022, 5:04 PM
Jayakrishna 🇼🇳
+ 1
messiest code ive ever seen, even worse than your average java code đŸ€ą
16th Apr 2022, 5:11 PM
Spritzenkopf