Hey guys this is my code until now, which outputs <function middle_element at 0x7f2cf8573e18>. I was wondering, I totally forgot, how do I display the value of this list?
This is my code:
#Write your function here
def middle_element(lst):
if len(lst) % 2 == 0:
return str(middle_element)
else:
return str(middle_element) / len(lst)
#Uncomment the line below when your function is done
If you’re posting code to the forums please see- How do I format code in my posts? Without the formatting it is much harder for anyone else to understand.
Be careful with names here. You have a function called middle_element. Inside that function you use the name middle_element, which refers to the function…
That’s probably not what you want.
Consider how to actually get the middle element. If you can’t solve it with code at first try it with pen and paper. Once you have a solution there it’s a matter of translating that to code which is often easier than going head-first and trying to do two tasks at once.
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]))
Why, in “sum”, does the second integer get subtracted by 1 rather than have 1 added to it? For instance, if I have a list of 12 integers, the first integer of “sum” here would pull the 6th item in the list. If I want the average of the middle two integers, wouldn’t I want to average the 6th and 7th integers? And in that case, wouldn’t I want the second part of “sum” to be:
lst[int(len(lst)/2) + 1]
? I can’t figure out why subtracting the second integer in “sum” by 1 would give us the next item in the list instead of the previous one.
EDIT: I forgot lists are 0-indexed. So the 6th indexed item in a 12 item list is actually the 7th item. Then I subtract one index position and come up with the 6th item. I’m leaving this up in case someone else has the same issue, however simple the error. Learning!