Here a suggestion:

def middle_element(lst):

if len(lst) % 2 != 0:

return lst[int(len(lst)/2)]

else:

return (lst[int(len(lst)/2)-1] + lst[int(len(lst)/2)])/2

Here a suggestion:

def middle_element(lst):

if len(lst) % 2 != 0:

return lst[int(len(lst)/2)]

else:

return (lst[int(len(lst)/2)-1] + lst[int(len(lst)/2)])/2

Is there a better way to learn/practice python math functions where the code challenges are actually reflective of the syntax/examples that were in the lesson? Instead of crazy math problems that are not even is the same universe as the lessons given? Any recommendations? Suggestions? I’m looking for somewhere to gradually get good at these math functions.

8 Likes

My solution to this… I think, it’s a bit different aproach, maybe someone finds it helpful ^^

def middle_element(lst):

return (lst[int(len(lst)/2)]+lst[int(len(lst)/2-0.5)])/2

that’s all

Can someone help me with this code of mine

def middle_element(lst):

if len(lst) % 3 == 0:

return lst[int(len(lst)/2)]

else:

sum= lst[int(len(lst)/2)] + lst[int(len(lst)/2)-1]

return sum/2

if i swap the if and else with the modulus 2 instead the code works fine but not the other way around

Is there any particular reason why you want to know whether the length is divisible into 3 equal parts?

If you’re looking for ONE value, then you want ONE value, plus whatever is on the right, and whatever is on the left. For there to be a value at all, there has to be an extra value after dividing into two parts.

So my thinking process was to check for odd numbers. for even we do number%2 if it is equal to 0 then it is even. likewise it should be true for odd numbers with the modulus of 3. ?

What does odd mean? What is the definition of odd?

1 Like

Ughh true true. sorry I wasnt thinking striaght. Thanks for pointing it out Cheers !!

I’m getting the right result but I can’t advance… What am I doing wrong?

def middle_element(lst):

if len(lst) % 2 == 1:

middle = len(lst) / 2

return lst[middle]

if len(lst) % 2 == 0:

middle = int(len(lst) / 2)

return (lst[middle-1] + lst[middle])/2